Tag Archives: Xamarin iOS

Creating an identical Custom Navigation Bar Back Button in Xamarin iOS…

Now there comes a time when the Developer has to override or customize the Back Button in their Xamarin iOS app. Well I’ve been there, hence let me share my experience…

Now the origin of my experience is that, I wanted to override the Back button click event of my Xamarin iOS, but since there’s no way to actually “override” the back button event, I had to completely get rid of the default back button and implement my own custom back button, but it had to be exactly similar as the original iOS back button…

45ffk

So let me ask you…

Have you ever wanted to override your Navigation Bar Back button in iOS  with Xamarin? or specially override it with an identical or similar looking custom button? may be to gain control of the Back button click event?

Then this post is for you… 😀

tumblr_inline_nl7ryzqono1rkrh6k

Custom, but Similar to the actual Back Button…

Yes that’s right, let me highlight the identical or similar looking custom back button, because it’s pretty simple and straightforward to override or replace the back button, but its a bit of struggle when you want to implement a custom back button which looks identical or similar to the original back button in iOS.

The key…

So the key things to keep in mind is that,

  • We need use an Image with a “Back Arrow” that is similar from look and size of the original back button.
  • Use similar Font size to display the Text
  • Use necessary padding and x/y values to place the Image and Text Title properly

Alright, let’s get into it…

Image with Back Arrow…

Now to find the image for the Back Arrow just google “iphone back button png” or something similar, you could easily find lots, I would recommend to use the icons8 website, which is where I got mine, https://icons8.com/web-app/15157/back

Make sure there’s no padding between the Image pixel space and the borders, in my case the image was 24×41 size

screen-shot-2017-03-02-at-1-09-15-pm

Oh another thing, make sure the Image is PNG, White color with a transparent back ground, so that you can edit the Tint as you go later if needed… 🙂

Title Text Font…

So for this one, I had to do a bit of playing around, which I found that “HelveticaNeue” and Font Size 17 is perfect for this. 🙂

Time for the coding… 😉

So let’s start off with loading the UIImage and initializing our UIButton.

// Load the Back arrow Image
var backBtnImage = UIImage.FromBundle("iosbackarrow.png");

backBtnImage = 
	backBtnImage.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);

// Create our Button and set Edge Insets for Title and Image
var backBtn = new UIButton(UIButtonType.Custom)
{
	HorizontalAlignment = UIControlContentHorizontalAlignment.Left,
	TitleEdgeInsets = new UIEdgeInsets(11.5f, 15f, 10f, 0f),
	ImageEdgeInsets = new UIEdgeInsets(1f, 8f, 0f, 0f)
};

 

And set up the necessary Edge Insets for the button Title and Image as shown above. Well those values I figured out by playing around with the positioning values for hours.. 😛 lol

Next let’s dive into the Button’s customization…

// Set the styling for Title
// You could set any Text as you wish here
backBtn.SetTitle("Back", UIControlState.Normal);
// use the default blue color in ios back button text
backBtn.SetTitleColor(UIColor.FromRGB(0, 129, 249), UIControlState.Normal); 
backBtn.SetTitleColor(UIColor.LightGray, UIControlState.Highlighted);
backBtn.Font = UIFont.FromName("HelveticaNeue", (nfloat)17);

// Set the Image to the button
backBtn.SetImage(backBtnImage, UIControlState.Normal);

// Allow the button to Size itself
backBtn.SizeToFit();

 

Alright, that’s quite a bit of code to swallow, so first we set the Title Text of the button, and keep in mind you could set any Text as you wish there, for now I’m just using “Back” text.. 🙂

Next for the Text Color in the Normal state, I have used the default Blue color variation that iOS use by default, you could also use any color you prefer as well 🙂 Next we set the Highlight state of Text to Light Gray.

As we discussed at the beginning we will use HelveticaNeue with Font size of 17 for the Title Text. And finally set the Image to the Button and allow it to fit to the required size. 😀

// Add the Custom Click event you would like to 
// execute upon the Back button click
backBtn.TouchDown += (sender, e) =>
{
	// Whatever your custom back button click handling
};

 

Now here’s something very important, we need to make sure we handle our custom back button click as shown above… 😉

So next we shall do the preparation for the Frame.

//Set the frame of the button
backBtn.Frame = new CGRect(
	0,
	0,
	UIScreen.MainScreen.Bounds.Width / 4,
	NavigationController.NavigationBar.Frame.Height);

// Add our button to a container
var btnContainer = new UIView(
	new CGRect(0, 0, backBtn.Frame.Width, backBtn.Frame.Height));
btnContainer.AddSubview(backBtn);

 

So there we are adding the Frame values to our Button, where as I’m setting the width to a quarter of the Screen width, and as of the Height, I’m retrieving the NavigationBar’s height for it.

Next we need to add our UIButton to a UIView container as show above and make sure it has the same Height and Width as our UIButton.

Time to wrap things up fellas…

// A dummy button item to push our custom  back button to
// the edge of screen (sort of a hack)
var fixedSpace = new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace)
{
	Width = -16f
};
// wrap our custom back button with a UIBarButtonItem
var backButtonItem = new UIBarButtonItem("", UIBarButtonItemStyle.Plain, null)
{
	CustomView = backBtn
};

// Add it to the ViewController
NavigationController.TopViewController.NavigationItem.LeftBarButtonItems 
= new[] { fixedSpace, backButtonItem };

 

So here’s the final steps, we are wrapping our button’s uiview container inside the UIBarButtonItem by setting it to the CustomView property. And then add it to the LeftBarButtonItems , which overrides the default existing Back Button.

Now you may wonder why there’s another UIBarButtonItem with the Width set to -16 value, this is actually to forcefully push our custom back button to the edge of the Navigation Bar. 😀 So that right, it is more of a hack to get the job done… 😉

See it in action…

So here’s our Custom iOS Back Button in action… 😀

screen-shot-2017-03-02-at-12-16-10-pm

Just for the sake of comparing here’s the default system Back Button in iOS…

screen-shot-2017-03-02-at-12-15-54-pm

Looks almost identical yeah! 😀

Well, that’s it fellas!

Enjoy! 😀

PS: I may have gotten some help from these posts on StackOverflow:

http://stackoverflow.com/questions/18384488/ios-7-uibarbutton-back-button-arrow-color
http://stackoverflow.com/questions/227078/creating-a-left-arrow-button-like-uinavigationbars-back-style-on-a-uitoolba

Advertisements

Animate a CATextLayer in Xamarin iOS

So this is a flash post about animating CATextLayer text color, or in descriptively animating ForegroundColor property of CATextLayer. 🙂 With Xamarin iOS!

Since this is a flash post I’m not going to explain what is CALayers or Core Animations of Xamarin iOS, rather let’s just jump into the code.

Using CABasicAnimation

Here’s the code…

// animate text color with CABasicAnimation
CABasicAnimation myCAbasicAnimation = CABasicAnimation.FromKeyPath("foregroundColor");
myCAbasicAnimation.SetFrom(UIColor.Blue.CGColor);
myCAbasicAnimation.SetTo(UIColor.Purple.CGColor);
myCAbasicAnimation.FillMode = CAFillMode.Forwards;
myCAbasicAnimation.Duration = 1.0f;
myCAbasicAnimation.RemovedOnCompletion = false;

// Add the animation to your CATextLayer
_myCAtextLayer.AddAnimation(myCAbasicAnimation, null);

 

So we basically set the FromKeyPath value which is the key value string for the property you want to target in your CATextLayer, in this case the “foregroundColor” as in the Text color.

Then we set the SetFrom and SetTo values, respectively the values to be animated in between. 🙂

Then if you want to remove this animation from your CATextLater upon completion, you could set the RemovedOnCompletion property to be true. Finally add the animation to your CATextLater by calling AddAnimation() and pass in the CABasicAnimation we just created. 😀

If you want to repeat and even reverse this animation, or put it in a loop, then use the below properties. 😉

myCAbasicAnimation.AutoReverses = true;
myCAbasicAnimation.RepeatCount = Single.PositiveInfinity;

 

TADAAAA! 😀

Using CATransaction

Here’s the code…

// animate text color with CATransaction
CATransaction.Begin();
// you could set CATransaction values by the key
CATransaction.SetValueForKey(new NSNumber(1.0f), CATransaction.AnimationDurationKey);
// or you could directly use properties AnimationDuration
//CATransaction.AnimationDuration = 1.0f;
_myCAtextLayer.ForegroundColor = UIColor.Purple.CGColor;
CATransaction.Commit();

 

This rather is rather good for animating a whole group of layers or animatable properties at the same time as an animation block. CATransactions are explicit where as you begin the modification layer upon Begin() call and finishes up on Commit() call.

That’s it. 😉

I guess in future I would be posting more of these “Flash Posts”, instead of lengthy explanatory articles due to work stuff. 😦 Hope for the best! 😀

How to add a fixed Background Image for a UIScrollView?

So recently I wanted to add a Fixed image behind a ScrollView in Xamarin Forms. Furthermore when the ScrollView is scrolling the background image shouldn’t scroll along with it, and background image should stay fixed while the content is scrolling.

Solution?

So the obvious solution would be to lay down a RelativeLayout and top of that Image, and then a ScrollView with Transparent background.

But I wanted…

but instead of laying out all those layouts and multiple controls, I wanted to achieve this right from one Control, by customizing the ScrollView accordingly.

So I got to into Coding…

So I created a Custom ScrollView control in PCL project and added the Custom Renderers for each platform iOS and Android. Although I got it working with ease in on Android by setting the Image as the Background drawable for the ScrollView, I was having some struggle with iOS.

trouble with iOS UIScrollView…

So the Xamarin Forms ScrollView’s native iOS mapped control is the UIScrollView. So I tried adding the a UIImageView to the UIScrollView from the custom renderer hoping it should get the job done according to theory.

but the background was panning across the Content size. And it started scrolling alone with the Content.

So let me walk you through what I tried and what actually worked… 🙂

1. Adding the UIImageView as a SubView

So as per the obvious solution I added the UIImage into a UIImageView and added it into the UIScrollView as a SubView as shown below. Also you may have noticed how I have called SendSubviewToBack method to place the UIImageView behind the UIScrollView.

protected override async void OnElementChanged(VisualElementChangedEventArgs e)
{
	base.OnElementChanged(e);

	if (e.NewElement != null)
	{
		var _uiImageViewBackground = new UIImageView(_uiImageBackground);

		this.AddSubview(_uiImageViewBackground);
		this.SendSubviewToBack(_uiImageViewBackground);
	}
}

 

And this was the result as you can see below..

method1

As you can see the UIImageView takes up the Height of the UIScrollView Content, not the UIScrollView actual Height, thereby resulting of the UIImageView spanning across the whole Content size. :O

2. Resizing the UIImage and adding the UIImageView as a SubView

Then I thought what if I resized the Image to the actual Height and Width of the UIScrollView and added as a Subview as show below.

Now in an iOS Custom Renderer we can not access the UIScrollView’s Bounds or Frame right from the OnElementChanged method, we need to override the Draw() method, which provides the Height and Width since it’s actually being drawn on the Parent view.

public override void Draw(CGRect rect)
{
	base.Draw(rect);

	// resize the UIImage to fit the current UIScrollView's width and height
	_uiImageBackground = ResizeUIImage(_uiImageBackground, (float)rect.Width, (float)rect.Height);

	var _uiImageViewBackground = new UIImageView(_uiImageBackground);

	this.AddSubview(_uiImageViewBackground);
	this.SendSubviewToBack(_uiImageViewBackground);
}

 

So as you can see I have resized the UIImage and added it to the UIScrollView thought a UIImageView holder.

Look at the results…

method2

Well the Background Image has been resized but the Background View still scrolls with the Content of UIScrollView. 😦

3. How about InsertSubview() ?

There are couple of methods for Adding a SubView to a View, the most common used one is the AddSubView() method which is also an alias for Add().

Then there also another method call we could use, InsertSubview(). In theory it does the same thing as AddSubView() but in a different manner where you could define a View index, in terms of which index the View should be added to in the array of sub-views in the given View.

So instead of this,

this.AddSubview(_uiImageViewBackground);
this.SendSubviewToBack(_uiImageViewBackground);

 

Let’s call the below, as you can see I’m placing our UIImageView at the very bottom of the SubViews stack by giving index 0 value.

this.InsertSubview(_uiImageViewBackground, 0);

 

Oh well what did you expect! Same result as before. 😦

4. How about InsertSubviewBelow() ?

So this method is also somewhat similar to above, where as this allows you to straightaway as a Subview, and define underneath which SubView you need to add your View in the stack. 😀

So I tried this as well. By the “this” reference I’m referring to the UIScrollView as the sibling and to tell the layout engine to place the UIImageView below the UIScrollView. 🙂

this.InsertSubviewBelow(_uiImageViewBackground, this);

 

But unfortunately the results was the same… 😦

5. What about directly setting the Background?

Frustrated with trying to add SubViews approach, I thought of directly setting the Background property of UIScrollView, specifically set the UIImage directly to the BackgroundColor Property of UIScrollView.

Well there’s no way we could set the BackgroundColor property from the Draw() method override, hence the canvas is already drawn. So we need to set it before its being drawn.

So let’s move back to the OnElementChanged method and set the BackgroundColor.

Since there’s no availability of the Height and Width values within the OnElementChanged event firing, for now we’ll just directly set the UIImage to BackgroundColor without resizing.

protected override async void OnElementChanged(VisualElementChangedEventArgs e)
{
	base.OnElementChanged(e);

	if (e.NewElement != null)
	{
			this.BackgroundColor = UIColor.FromPatternImage(_uiImageImageBackground);
	}
}

 

Oh well, look at the results. It also fills up the whole Content area, without just setting the “background” on UIScrollView.

method3

5. What about directly setting the Background with resized UIImage?

Alright now let’s get a bit serious and retry the above approach properly, by accessing the Height and Width of the UIScrollView and resizing the UIImage accordingly.

So to do this we need to tap into the place where the Height and Width first gets allocated before the Draw method. That’s by subscribing to the OnPropertyChanged() as shown below.

protected override async void OnElementChanged(VisualElementChangedEventArgs e)
{
	base.OnElementChanged(e);

	if (e.NewElement != null)
	{
		((CustomScrollView)e.NewElement).PropertyChanged += OnPropertyChanged;
	}
}

private void OnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
	if (propertyChangedEventArgs.PropertyName == CustomScrollView.HeightProperty.PropertyName)
	{
		// check if the Width and Height are assigned
		if (((CustomScrollView)sender).Width > 0 & ((CustomScrollView)sender).Height > 0)
		{
			// resize the UIImage to fit the current UIScrollView's width and height
			_uiImageImageBackground = ResizeUIImage(_uiImageImageBackground, (float)((CustomScrollView)sender).Width, (float)((CustomScrollView)sender).Height);

			// Set the background Image
			this.BackgroundColor = UIColor.FromPatternImage(_uiImageImageBackground);
		}
	}
}

 

So inside the OnPropertyChanged() event we are waiting till the Width and Height properties are available, as you can see we are looking for the PropertyName in the event args. Then we resize the UIImage according to the retrieved Height and Width and values of UIScrollView and set the UIImage to the Background.

method4

Now as you can see, the Background Image gets resized to the exact size of UIScrollView but the Background is still scrolling with the content. And if you notice closely, you can see the Background has repeated the Image, this is because of the UIColor.FromPatternImage() where as the UIImage gets repeated to fill the whole canvas. This means that the Background still gets spread across the whole Content area of the UIScrollView.

then I witnessed something strange….

What actually worked… (strangely though)

So meanwhile playing around with different override methods and properties, at some point….

I accidentally left the Draw() method overridden in my Custom Renderer as shown below, and moved the setting of the UIScrollView Background to the OnPropertyChanged event like I did in the previous step.

protected override async void OnElementChanged(VisualElementChangedEventArgs e)
{
	base.OnElementChanged(e);

	if (e.NewElement != null)
	{
		((CustomScrollView)e.NewElement).PropertyChanged += OnPropertyChanged;
	}
}

private void OnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
	if (propertyChangedEventArgs.PropertyName == CustomScrollView.HeightProperty.PropertyName)
	{
		// check if the Width and Height are assigned
		if (((CustomScrollView)sender).Width > 0 & ((CustomScrollView)sender).Height > 0)
		{
			// resize the UIImage to fit the current UIScrollView's width and height
			_uiImageImageBackground = ResizeUIImage(_uiImageImageBackground, (float)((CustomScrollView)sender).Width, (float)((CustomScrollView)sender).Height);

			// Set the background Image
			this.BackgroundColor = UIColor.FromPatternImage(_uiImageImageBackground);
		}
	}
}

//We need to override this to have the background image to be fixed
public override void Draw(CGRect rect)
{
	base.Draw(rect);
}

 

As you can see in my above code, I have just overriden the Draw() event and left it just as it is, without writing any code inside the method.

And behold! 😀 IT WORKED! 😀

bloopscrollview-on-ios-lowq

TADAA! 😀 as you can see we have successfully got it to work, a fixed background image in UIScrollView. 😉

Although this does not make any sense, how could the Background of the UIScrollView prevents itself from scaling to the size of Content size just by simply overriding the Draw() event, without even executing any code inside of it.

Either way this trick got the work done. 😀 May be this is just a bug in Xamarin or iOS. 😛

There you have it, how to add a fixed background image to a UIScrollView from custom renderer in Xamarin! 🙂

Enjoy!

Want to play a Vimeo Video in your Xamarin iOS app ? ;)

Remember my previous article on Let’s add a Video Stream Player to your Xamarin iOS App… ? 😀 Do you remember? If not check it out! It’s pretty cool! 😛

Anyways have you ever wanted to play a Vimeo video in your app? 😉 Question is probably yes and if you were redirected from Google, then you are already looking for it. lol 😀

The first time my boss asked me to do this, I was like.. huh? O.o Vimeo videos are played by streaming directly from their servers, how am I suppose to implement that in a mobile app, unless they have any 3rd party library, or adopt a bad practice such as implementing a web view to display the video with an embedded frame in it.

Yes it is a common requirement to attach an online video to your mobile app, such as from streaming giants as Youtube, Vimeo and etc. And for most of them have many third party libraries to consume their services such as streaming those videos, but only for native Mobile development.

But… what about Cross-Platform? ummm… Xamarin?  😦

Well it’s not impossible, there’s always a way! 😉

So today I’m gonna show you how you could play a Vimeo video in your Xamarin App.

First of all, if you haven’t implemented the Video player for your Xamarin app, then you may do as I did,  Let’s add a Video Stream Player to your Xamarin iOS App (but that’s for Xamarin iOS) and you could find a tutorial for Xamarin Android right here,Video player implementation for Xamarin Android.

Little something about Vimeo Videos…

When you consider a Vimeo video, it surely has the capability for streaming…

And also you could retrieve a static endpoint of the actual Video Source with extension.

but in order to retrieve you need to be the administrator of the account that posted this video. So this URL endpoint is what we are going to be using for our Video Player.

In my situation I had to play the Vimeo video which was posted by an account which I had the administrator access. But I couldn’t find if there’s any other ways to retrieve the static endpoint url for the video without having admin access to the Video you need to play.
So keep in mind it is crucial you have the admin access for the Vimeo account which had posted the video.

So how?

First log into your Vimeo account. Go to the Video you want to be played in your Mobile App. Click on the “Settings” button at the bottom of the video, in order to access Settings.

vimeo1

Once you’re in the Settings section of that video, click on the “Video File” tab.

vimeo2

Which will take you to the properties of the actual Video file of your Vimeo Video. Now pay attention to the bottom of the page here, where you’ll notice the “Access your Video files” section.

vimeo3

Yep right there is your savior, which will provide you with the endpoint URL with the extensions for your video, specially in different kinds of quality, HD or SD or even Live Streaming link.

So for our requirement we are going to be using the High Definition or the Standard Definition, based on your choice. Go ahead and copy the URL and use it as the Video source for your Video Player implementation in Xamarin. 🙂

vimeo4

Well that’s it! Simple as that! 😉

Hope this helped someone not to waste hours and hours by trying to implement WebView Embedded player for playing a simple Vimeo Video. 🙂

Cheers! 😀

Let’s add a Video Stream Player to your Xamarin iOS App…

So you wanna add an Online Video Player for your Xamarin iOS app ? How hard could it be, just add a WebView and screw up the whole thing right ? 😉 lol
Stream an online video? from Youtube? Vimeo? or wherever?

Yep one day I was given a task by my boss to implement a Video Player in one of our Xamarin iOS apps, that could play an online video…

So basically our app should be able to play an online video within the application frame. Add a Video Player control to the Xamarin iOS app but it should have all the controls with in the page itself, and more specifically this Video Player should be able to play Online Video, as in should be able to stream an Online Video over the internet. :O

Solution ?

After going through the Xamarin documentation, to my surprise I found out about this control that Xamarin provides called MPMoviePlayerController, which is like a built in controller for playing Videos, but in their documentation they had shown only an example of how to play a ‘locally stored video file’. Seriously? Who would wanna store a video file locally nowadays? 😛 lol

Anyhow, with a bit of uncertainty, I implemented this control, and after a bit of a struggle, I finally got it to working! 😀

So as usual, here I am sharing my experience with you guys… Hold on tight, it’s about to get bumpy! 😉

How to implement…

So basically we need to create an instance of the MPMoviePlayerController as follows, to be able to access it from any other methods in our ViewController, so that we could control the actions of the MPMoviePlayerController.

public class BlahBlahViewController : UIViewController
{
	MPMoviePlayerController moviePlayer;

	public BlahBlahViewController()
	{

	}
}

 

Next let’s go ahead with the implementation of the MPMoviePlayerController

// first define the Online Video URL you want to play 
var urltoplay = new NSUrl("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
moviePlayer = new MPMoviePlayerController();
// set the URL to the Video Player
moviePlayer.ContentUrl = urltoplay;
moviePlayer.View.Frame = new CGRect(55, 170, 310f, 200f);
// Set this property True if you want the video to be auto played on page load
moviePlayer.ShouldAutoplay = false;
// If you want to keep the Video player on-ready-to-play state, then enable this
// This will keep the video content loaded from the URL, untill you play it.
moviePlayer.PrepareToPlay();
// Enable the embeded video controls of the Video Player, this has several types of Embedded controls for you to choose
moviePlayer.ControlStyle = MPMovieControlStyle.Embedded;

View.AddSubview(moviePlayer.View);

 

As you can see above, this MPMoviePlayerController a lot of flexible customization and features for us to implement. Notice that PrepareToPlay() method will set the Video Player in a ready state to play the video on click. (It’s actually a nice option).
Also keep a note that you could choose any type of ControlStyle as you like as it provides a several options for the embedded controls of the Video Player.

Keep in Mind…

When you provide the Online Video URL to the control, make sure that URL has a video file extension for it. Otherwise this will not work, hence it requires the file extension for the video to be played. This control does not support direct Youtube or Vimeo video playing with their web browser link, you need to provide the online FTP location of the video to be played. 🙂

A little Cherry on top…

Now to put some cherry on top of the basic implementation I added some extra functionality by adding few custom buttons to control the Video Player implementation.

var playButton = UIButton.FromType(UIButtonType.RoundedRect);
playButton.Frame = new CGRect(10, 380, View.Bounds.Width - 20, 44);
playButton.SetTitle("Play Video", UIControlState.Normal);
playButton.BackgroundColor = UIColor.White;
playButton.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
playButton.TouchUpInside += delegate
{
	moviePlayer.Play();
};
View.AddSubview(playButton);

var playFullScreenButton = UIButton.FromType(UIButtonType.RoundedRect);
playFullScreenButton.Frame = new CGRect(10, 420, View.Bounds.Width - 20, 44);
playFullScreenButton.SetTitle("Play Full Screen Video", UIControlState.Normal);
playFullScreenButton.BackgroundColor = UIColor.White;
playFullScreenButton.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
playFullScreenButton.TouchUpInside += delegate
{
	moviePlayer.Play();
	// To play full screen
	moviePlayer.SetFullscreen(true, true);
};
View.AddSubview(playFullScreenButton);

var stopButton = UIButton.FromType(UIButtonType.RoundedRect);
stopButton.Frame = new CGRect(10, 460, View.Bounds.Width - 20, 44);
stopButton.SetTitle("Stop Video", UIControlState.Normal);
stopButton.BackgroundColor = UIColor.White;
stopButton.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
stopButton.TouchUpInside += delegate
{
	moviePlayer.Stop();
};
View.AddSubview(stopButton);

var pauseButton = UIButton.FromType(UIButtonType.RoundedRect);
pauseButton.Frame = new CGRect(10, 500, View.Bounds.Width - 20, 44);
pauseButton.SetTitle("Pause Video", UIControlState.Normal);
pauseButton.BackgroundColor = UIColor.White;
pauseButton.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
pauseButton.TouchUpInside += delegate
{
	moviePlayer.Pause();
};
View.AddSubview(pauseButton);

 

There you have it, a four button implementation for controlling the Video playing of MPMoviePlayerController.

As you may have noticed in the ‘Play Full Screen Video’ button action, I have called the method moviePlayer.SetFullscreen(true, true); which allows us to play the video in full screen mode. Once the click even fires, the Video controller will nicely stretch itself to the fullscreen of the app and play the video.

Alright, now let’s see how this actually looks after the implementation.

Here’s how it’ll look like… 😀

hustle hustle (1)

there you everyone, now go crazy with it. 😉

Here’s something extra…

Did you know you could detect the state changes in the MPMoviePlayerController and control its behavior ? Yes MPMoviePlayerController has a set of Observable notification methods that we could register and use for our own needs as follows.

// Register yourself for the observable notifcations
MPMoviePlayerController.Notifications.ObservePlaybackStateDidChange(MediaPLayer_OnPlaybackStateDidChange);
MPMoviePlayerController.Notifications.ObservePlaybackDidFinish(MediaPLayer_OnPlaybackComplete);

.....

// And do whatever you want based on the events

// For and example here I'm automatically setting the player to the full screen  when it starts Playing
private void MediaPLayer_OnPlaybackStateDidChange(object sender, NSNotificationEventArgs e)
{
	if (moviePlayer.PlaybackState == MPMoviePlaybackState.Playing)
	{
		moviePlayer.SetFullscreen(true, true);
	}
}

// Another example, automatically exiting the full screen when the Play back completes
private void MediaPLayer_OnPlaybackComplete(object sender, MPMoviePlayerFinishedEventArgs e)
{
	moviePlayer.SetFullscreen(false, true);
	moviePlayer.View.Hidden = true;
}

 

Yep there you go another set of awesome features we could play around in MPMoviePlayerController.

Parallels Picture

There’s a whole set of Observable events you could register yourself to based on your requirements and to play around with! 😉

Cheers!

Stay awesome! 😀

Setting the NavigationBar colors in Xamarin.Android and Xamarin.iOS

WOOT! WOOT! This is regarding my previous post on Setting the NavigationBar colors in Xamarin.Forms!

So I thought it might be handy for some of you to know how to set the NavigationBar colors in Xamarin.Android and Xamarin.iOS! And oh, I’m not going to tell you about the reasons why you would ever want to do this and blah blah as I have mentioned that already in my previous post. lol 😛

When it comes to Xamarin Native level there’s a huge advantage with in-depth customization for any controllers and properties. Therefore some of you might want to dive into the custom renderers when you customize the Navigation Bar and so on. Or may be you are doing a development on native Xamarin.Android app or native Xamarin.iOS app, thereby you may be in need of customizing the NavigationBar (iOS) or the ActivityBar (Android) respectively. However the reasons, let’s get down to business.. 😀

NavigationBar Customization in Xamarin.iOS …. 🙂

Yes in iOS we refer to the NavigationBar just as it is, lol and you could easily customize it by referring to the UINavigationBar.Appearance property.
Here’s some sample customization you could do using these properties, but keep in mind you could constomize this very easily and in-detail according to your preferences, just a matter of a playing around 😉 

// Setting (NavigationBar) Toolbar background color natively
UINavigationBar.Appearance.BarTintColor = Color.FromHex("#ff5300").ToUIColor();
UINavigationBar.Appearance.TintColor = UIColor.White;
UINavigationBar.Appearance.SetTitleTextAttributes(
	new UITextAttributes { TextColor = Color.White.ToUIColor() });

 

ActionBar Customization in Xamarin.Android …. 🙂

Oh Yes! in Android we could refer to the ActionBar via the Context instance or may be if you are inside of an Activity, you could directly static reference it, to access its various Set properties for customization. Here also you could go in-detail according to your preferences, just a matter of a playing around 😉

// Setting ActionBar (Toolbar) background color natively
var actionBar = ((Activity)Context).ActionBar;
actionBar.SetBackgroundDrawable(new ColorDrawable(Xamarin.Forms.Color.FromHex("#ff5300").ToAndroid()));

 

WOOT! WOOT! There you go! 😀

Oh well just another tiny blog post in a boring day I guess.. lol

Cheers!

Stay Awesome! 😀

 

Setting the NavigationBar colors in Xamarin.Forms

Have’t you ever got bored of the default colors of the Navigation bar of your applications ? 😛 Well I know I did, so as my boss in the new company I’m working for. lol

Enough chit chat! Lemme show you how to change the background color of the default Navigation bar in our awesome Xamarin Forms framework.

Yes it’s crazy simple nowadays, as Xamarin has allowed us to control that from the PCL level itself. But earlier I recall it was pretty complex where we had to write custom renderers and stuff.

How to… from C# code level ?

Xamarin has introduced the following properties for this job, BarBackgroundColor, and BarTextColor. You could easily set these properties for your NavigationPage instance and woahlah ! You are done.

public App()
{
	MainPage = new NavigationPage(new Page1())
	{
		BarBackgroundColor = Color.FromHex("#ff5300"),
		BarTextColor = Color.White,
	};
}

 

Alright now, hit Run and check it out fellas !

Behold…

Nexus 4 (Lollipop) Screenshot 1  Simulator Screen Shot 4 Feb 2016, 12.28.46 PM

Oh look at that gorgeous NavigationBar… Such an eye-candy view.. lol

Alright looks good… moving on… 😛

How to… from XAML code level ?

What if you wanted to set these properties in XAML level ? 😀

Well to tell you a little story, the project I’m working now is pretty complex and the architecture is super awesome, that we have to dive massively into MVVM and Architectural design stuff… So we usually keep all the UI related stuff in XAML level. 😉 So yeah this is how I originally implemented it, but I did the C# code stuff just to show the separation. End of Storytime ! lol 😛

So here’s how to handle this in XAML…

  <App.Resources>
    <ResourceDictionary>
      
      <!-- Styles -->
      <Style TargetType="NavigationPage">
        <Setter Property="BarBackgroundColor" Value="#ff5300"/>
        <Setter Property="BarTextColor" Value="White"/>
      </Style>
      <!-- Styles -->

	</ResourceDictionary>
  </App.Resources>

 

You simply put those values in your global Style level, so when the app is running it will fetch them from those values and set it to the navigation bar.

TADAAAAA ! 😀

That’s it… Cheers!

Stay Awesome developers !

Handling Push Notifications in Xamarin iOS when App is Closed…

Few months back I wrote an article on implementing Push Notification in awesome Xamarin Forms, So I just implemented Push Notifications in awesome Xamarin.Forms … 😉 after my personal experience at work. And YES ! it works like a charm without any doubt.

Something Spooky…

But after a while I noticed something in Xamarin iOS app, whereas when we send out the Push Notification from Azure Hub, the notification gets received by iPhone, and when I click on the Notification alert, it gets opened up in the app and displays the redirected page. But sometime, when I click on the received push notification alert, the app opens up, but the push notification message box doesn’t get displayed or gets redirected to the message display page. In short, sometimes the push notification alert click only opens up the app, nothing else.

Okay What is happening…

After careful observation I noticed that, when the app is running or if its in the background, and I click on the push notification alert, it gets opened up in the app and everything works fine. But when the app is closed or not running in the background, the push notification alert only opens up the app, and it doesn’t get redirected to the message display page or anything.

But Why is this happening…

I realized this after going through the push notification alert click event, which is ReceivedRemoteNotification() 

Capture

This method gets fired when the User clicks on the received push notification alert on the phone. And from there it calls the ProcessNotification method where it displays the Push Notification alter Message Box and redirects the user to the give page in the app.

But it gets fired only when the app is already running or if its running in the background stack. If you have restarted the phone or closed the app or by any chance if the app is not running in the background, this method will not get fired upon above push notification action. And thereby it will only open up the app. 😦

So What is the Solution…

So what we need to do here is to detect at the FinishedLaunching() method whether the app was opened up by a Push Notification alert click or manual app icon click by the User.

This is a common scenario most of the developers has faced, not only in Xamarin Forms related iOS even in native iOS development. But most of us don’t realize this as it’s very hard to notice this scenario, because we usually don’t manually close apps in our iPhone devices. Even I got curious about this when my boss complained about this once, and yes took me a while to figure it out too… 😉

Alright ! Let’s patch it up !

Even though it took me a while to figure out the solution, it was quite simple to implement. The reason I’m sharing this is because there’s not much resources regarding this issue, probably because we don’t easily notice this issue.

This solution can be implemented easily for anyone even without following my previous Xamarin Forms push notifications implementation article, just do the changes as shown below, then you should be good to go. I’m not going to repost the whole code here, but only the necessary changes, but if you are looking for the full code, you may check up my article,  So I just implemented Push Notifications in awesome Xamarin.Forms !
Let’s begin…

Did you know, when our iOS app is closed and it gets opens up by the click on a Push Notification Alert, the system passes through a parameter in the NSDictionary options parameter in the FinishedLaunching() method which is called UIApplicationLaunchOptionsRemoteNotificationKey !

All we have to do is capture this parameter value in our FinishedLaunching() method and process the notification. Inside this key object contains the whole push notification object which we could easily extract. So add the following code to the end of your FinishedLaunching() method in AppDelegate class.

// Handling Push notification when app is closed if App was opened by Push Notification...
if (options != null && options.Keys != null && options.Keys.Count() != 0 && options.ContainsKey(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey")))
{
	NSDictionary UIApplicationLaunchOptionsRemoteNotificationKey = options.ObjectForKey(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey")) as NSDictionary;

	ProcessNotification(UIApplicationLaunchOptionsRemoteNotificationKey, false);
}

 

As you can see above we are checking for the existence of the UIApplicationLaunchOptionsRemoteNotificationKey object key value in the options parameter of FinishedLaunching() method. After extracting the object we are passing it to our usual ProcessNotification() method in order to do the usual processing of the push notification message.

After that tiny trick your FinishedLaunching() method should look like this… 🙂

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
	if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
	{
		var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
						   UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
						   new NSSet());

		UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
		UIApplication.SharedApplication.RegisterForRemoteNotifications();
	}

	else
	{
		UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
		UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
	}

	global::Xamarin.Forms.Forms.Init();

	LoadApplication(new App());

	// Handling Push notification when app is closed if App was opened by Push Notification...
	if (options != null && options.Keys != null && options.Keys.Count() != 0 && options.ContainsKey(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey")))
	{
		NSDictionary UIApplicationLaunchOptionsRemoteNotificationKey = options.ObjectForKey(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey")) as NSDictionary;

		ProcessNotification(UIApplicationLaunchOptionsRemoteNotificationKey, false);
	}

	return base.FinishedLaunching(app, options);
}

 

Well there it goes folks, hope this post was helpful for you and prolly saved you a lot of time… 🙂 Please share this among other developers as there aren’t much resources on Handling Push Notifications in Xamarin iOS when App is Closed, and you may save another developer’s time as well… 😉

Stay awesome fellow Geeks ! ^_^

Google Analytics tracking implementation in Xamarin …

It all began a while back when my boss tasked me to implement Google Analytics Tracking in one of the enterprise mobile applications we were developing using Xamarin platform, and to be specific the whole app was based on Xamarin Forms platform, harnessing the true cross platform abilities of Xamarin…

Since the first day of the development, it’s been a bit hard but a massive learning curve, due to the lack of articles regarding Google Analytics implementation in Xamarin, specifically Xamarin Forms. And yes, I did go through some back and forth mess, as for the lack of resources… But somehow I managed to successfully implement Google Analytics Tracking in our Xamarin based enterprise application.

Therefore I decided to share the experience and the knowledge I gained, with our fellow Xamarin Developer Community and ultimately save the precious time of a another developer, with the hopes of filling the gap of the lack of articles in Google Analytics implementation in Xamarin. 🙂 So here is the series of articles I wrote in that pursue…

Google Analytics implementation in Xamarin Android –

Let’s add Google Analytics to your Xamarin Android App ^_^

Untitled-1

https://theconfuzedsourcecode.wordpress.com/2015/07/06/lets-add-google-analytics-to-your-xamarin-android-app-_/

Google Analytics implementation in Xamarin iOS –

Let’s add Google Analytics to your Xamarin iOS App ^_^

Untitled-2

https://theconfuzedsourcecode.wordpress.com/2015/07/09/lets-add-google-analytics-to-your-xamarin-ios-app-_/

Google Analytics implementation in Windows Phone –

Let’s add Google Analytics to your Windows Phone App ^_^

Untitled-3

https://theconfuzedsourcecode.wordpress.com/2015/07/17/lets-add-google-analytics-to-your-windows-phone-app-_/

Google Analytics implementation in Xamarin Forms –

Okay Finally, Let’s add Google Analytics to Xamarin Forms …

Untitled-1

https://theconfuzedsourcecode.wordpress.com/2015/07/18/okay-finally-lets-add-google-analytics-to-xamarin-forms/

Well there it goes… Google Analytics tracking implementation in Xamarin ! 🙂

Well there it goes folks, hope this post was helpful for you and prolly saved you a lot of time… 🙂 Please share this among other developers as there aren’t much tutorials on Google Analytics tracking for Xamarin, and you may save another developer’s precious time as well… 😉

Cheers ! Stay Awesome ^_^ !

Let’s add Google Analytics to your Xamarin iOS App ^_^

After my previous post about how to add Google Analytics to your Xamarin Android app, I thought of writing an article for Xamarin iOS as well based on my own experience. 🙂

When I was implementing Google Analytics in one of my Xamarin iOS projects, it wasn’t such a complicated process, thanks to the official Xamarin component for GA (Google Analytics) but then again, I couldn’t find much articles based on its code implementation, whereas I had to begin with simple example they have given in the Xamarin Component Store.

Untitled-2

Now the whole concept of the Google Analytics implementation in Xamarin iOS is pretty much same as the implementation in Xamarin Android, but the coding approach and syntax are different.

Therefore I thought of sharing my experience and coding approach with you fellow Xamarin developers out there, which I’m pretty sure will be very much helpful for you all. 😉

Setting up the Library…

First of all, follow me and praise the official Google Analytics component for Xamarin iOS… 😉 Go ahead download it..

https://components.xamarin.com/view/googleanalytics

Untitled2

Once you have downloaded, we need to add the DLLs to your project References. You can do that by navigating into the following path in the folder you downloaded and extracted the library files to, which should be something similar to this “C:\…\googleanalytics-3.0.12\googleanalytics-3.0.12\lib\ios-unified\”. Add the “GoogleAnalytics.iOS.dll” to your project references.

Please note that this is for the Xamarin iOS Unified SDK, not for the classic SDK ! 🙂 I wouldn’t be going into the class sdk as everyone is migrating to the ios unified SDK.

Let the Coding begin…

Just as I have done in my previous article, I recommend that you keep a separate class for handling all the Google Analytics functionalities. So go ahead and create GAService class. In this class we are gonna implement all the GA functionalities we need to execute.

As for initializing we need to have instances with in this class as below and make sure to add the tracking code you get from your Google Analytics dashboard to the TrackingId value…

public string TrackingId = "XX-XXXXXXXX-X";

public IGAITracker Tracker;
const string AllowTrackingKey = "AllowTracking";

 

As you can see above, except for the Google Analytics instance I have added a string called “AllowTrackingKey“, this is going to be used for allowing the user to opt out of the analytics tracking upon their choice. I have just added it to this code, for the sake of good practices, but you can remove it from here and later in the code implementation if you wish to.

In the constructor, we need to initialize the Google Analytics tracking service, and for that we need to have a reference and we do not need to pass in any references like we did in Xamarin Android. 🙂 Because in Xamarin GA it keeps a static shared instance of the GA tracking service where we can easy access.

public void Initialize()
{
	var optionsDict = NSDictionary.FromObjectAndKey(new NSString("YES"), new NSString(AllowTrackingKey));
	NSUserDefaults.StandardUserDefaults.RegisterDefaults(optionsDict);

	GAI.SharedInstance.OptOut = !NSUserDefaults.StandardUserDefaults.BoolForKey(AllowTrackingKey);

	GAI.SharedInstance.DispatchInterval = 10;
	GAI.SharedInstance.TrackUncaughtExceptions = true;

	Tracker = GAI.SharedInstance.GetTracker("Test App", TrackingId);
}

 

As you can see above I have used the previously explained AllowTrackingKey variable to give the user option to opt out from the Tracking events by adding it to the SharedUserDefaults.

Here we are using the Shared instance that Xamarin GA provides in order to instantiate it with our configuration. There up above as you can see I have set the Local dispatch period to “10”, which means all the tracking data will be automatically uploaded to the online GA service in every 10 seconds, this is a good approach considering we should not exhaust the network resources by uploading tracking information every single second. You can change the value to anything you wish but I recommend you keep it around this value.

For some reason exception for the AutoExceptionTracking I couldn’t find any methods or properties to enable AutoActivityTracking and AdvertisingIdCollection, like we did in Xamarin Android. Probably they can not be supported in iOS platform.

Now that we have done with the initialization, next let’s dive into coding the actions… 😉

Let’s track a Page View…

In order to track a Page you may need to add the following method to our GAService class.

public void Track_App_Page(String PageNameToTrack)
{
	GAI.SharedInstance.DefaultTracker.Set(GAIConstants.ScreenName, PageNameToTrack);
	GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateScreenView().Build());
}

 

As you can see above we are passing in the Page Name we need to track and we are setting it to our GA tracker instance . Then within the Send() method call we are creating a new Screen View with the GAIDictionaryBuilder (there are several types of GAI Dictionary Builders which you could use based on several types events you need to track), specifically calling the CreateScreenView(), which is used to create a new a screen view hit. Keep in mind whatever the name you pass in to the method will be recorded in Google Analytics, whenever we need to track a page view, we will be calling this method.

Let’s track an Event…

In order to track any Event, such as a button click, check box selection and son on, you can use the following method. This is very much likely how we did in Xamarin Android, but the syntaxes are a bit different.

In order to track an Event in Google Analytics, we need to have an Event Category, therefore we need to create a small struct along with the type of categories you need to track, this actually depends completely upon your requirement. You can have types of event categories such as. “Sales”, “Order”, “Shopping Cart” and so on… 🙂

public struct GAEventCategory
{
	public static String Category1 { get { return "Category1"; } set { } }
	public static String Category2 { get { return "Category2"; } set { } }
	public static String Category3 { get { return "Category3"; } set { } }
};

 

Now let’s implement the method, for this method we will be passing the above struct values for the GAEventCategory parameter. And for the EventToTrack parameter, you can send whatever event/ event description you want to record in Google Analytics.

public void Track_App_Event(String GAEventCategory, String EventToTrack)
{
	GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent(GAEventCategory, EventToTrack, "AppEvent", null).Build());
	GAI.SharedInstance.Dispatch(); // Manually dispatch the event immediately // just for demonstration // not much recommended 
}

 

As shown above we are using the GAIDictionaryBuilder with the CreateEvent method call to create a new event and we are setting up the category and event action as it’s passed in as parameters. Also you can set Labels in Google Analytics for any of your events, but as a general I have set the default label to “AppEvent”, but you can use labeling if you want to generate more complex and detailed tracking, where as Google Analytics is a truly great tool.

Also you may notice that I have called the method Dispatch() right at the bottom, this is just to show you that, we can manually dispatch the Analytics data on demand as we wish, without waiting for the default dispatch to occur. 🙂 Like wise even in other events you can call the dispatch method and immediate send the tracking data to GA servers, but I wouldn’t recommend that as it could clog up your bandwidth usage.

Let’s track an Exception…

Now we all know that exceptions O.o are such a nasty bastard in any application. And its a good habit to keep a track on them. As I have mentioned above,

GAI.SharedInstance.TrackUncaughtExceptions = true;

 

This Tacker setting captures all the Exceptions that occurs in the application, but keep in mind, this only tracks the unhandled exceptions. Now how about the handled exceptions ? what if we need to keep a track on a certain type of exceptions that’s already being handled in the application.

For such instances you may use the following piece of code… 😉 Just like we did in Xamarin Android, if you want to record an Exception event in Google Analytics, you need to mention whether it’s a Fatal Exception or not. Therefore you need to pass in a Boolean mentioning whether it’s fatal or not as coded in the below method.

public void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException)
{
	GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateException(ExceptionMessageToTrack, isFatalException).Build());
}

 

We are using the GAIDictionaryBuilder with CreateException method call for this hit in the same method I have used in the other two events above. And when you pass in the Exception message, you can either take the whole ex.StackTrace() or ex.Massage() or both together as a value of your exception in anyway you wish. 🙂 

And now just like we did in Xamarin Android we need to do some decorations to our GAService class…

Just a little decorating…

Now I have unified the access to the Google Analytics tracking by including all the methods in one single class, but in order to access it we need to instantiate right ? That’s why we need to add a little Singleton pattern decoration to our class. Or else you could also make the methods static and straightaway call them, but its your wish.. 🙂

#region Instantition...
private static GAService thisRef;
private GAService()
{
	// no code req'd
}

public static GAService GetGASInstance()
{
	if (thisRef == null)
	// it's ok, we can call this constructor
	thisRef = new GAService();
	return thisRef;
}
#endregion

 

Now that way we can keep a single instance and use it to execute all the functions.

After all that’s done your GAService class should look like this… 🙂

namespace WhateverYourNamespace
{
	public class GAService
	{
		public string TrackingId = "XX-XXXXXXXX-X";

		public IGAITracker Tracker;
		const string AllowTrackingKey = "AllowTracking";

		#region Instantition...
		private static GAService thisRef;
		private GAService()
		{
			// no code req'd
		}

		public static GAService GetGASInstance()
		{
			if (thisRef == null)
			// it's ok, we can call this constructor
			thisRef = new GAService();
			return thisRef;
		}
		#endregion

		public void Initialize()
		{
			var optionsDict = NSDictionary.FromObjectAndKey(new NSString("YES"), new NSString(AllowTrackingKey));
			NSUserDefaults.StandardUserDefaults.RegisterDefaults(optionsDict);

			GAI.SharedInstance.OptOut = !NSUserDefaults.StandardUserDefaults.BoolForKey(AllowTrackingKey);

			GAI.SharedInstance.DispatchInterval = 10;
			GAI.SharedInstance.TrackUncaughtExceptions = true;

			Tracker = GAI.SharedInstance.GetTracker("Test App", TrackingId);
		}

		public void Track_App_Page(String PageNameToTrack)
		{
			GAI.SharedInstance.DefaultTracker.Set(GAIConstants.ScreenName, PageNameToTrack);
			GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateScreenView().Build());
		}

		public void Track_App_Event(String GAEventCategory, String EventToTrack)
		{
			GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent(GAEventCategory, EventToTrack, "AppEvent", null).Build());
			GAI.SharedInstance.Dispatch(); // Manually dispatch the event immediately
		}

		public void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException)
		{
			GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateException(ExceptionMessageToTrack, isFatalException).Build());
		}
	}
}

 

Finally let’s FIRE IT UP… ! 😉

Well as our GAService class is ready, let’s see how to access it and start tracking our App. 🙂

You need to modify your FinishedLaunching method as follows,

public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
	window = new UIWindow (UIScreen.MainScreen.Bounds);

	GAService.GetGASInstance().Initialize();

	viewController = new HomePage ();
	navController = new UINavigationController (viewController);
	window.RootViewController = navController;
	window.MakeKeyAndVisible();
	
	return true;
}

 

As you can see above I am first of all initializing our Google Analytics services through the GetGASInstance() method.

Here is how you could use our above class for Page Tracking, Event Tracking and Exception Tracking.

// Track a page
GAService.GetGASInstance().Track_App_Page("Home Page");

// Track an event
GAService.GetGASInstance().Track_App_Event(GAEventCategory.Category1, "hey ! Category 1 type event ocurred !");   

// Track an Exception
GAService.GetGASInstance().Track_App_Exception(ex.Message, false); 

 

After calling those methods you will be able to see the live tracking information in your Google Anlytics Dashboard online. Just log in to the Real-Time Overview  and you will be able to see everything there. Just keep in mind, as there is a dispatch period of 10 seconds, it might take a while for the actual tracking data to be displayed in the Real-Time tracking view in Google Analytics… 🙂

Well there it goes folks, hope this post was helpful for you and prolly saved you a lot of time… 🙂 Please share this among other developers as there aren’t much tutorials on Google Analytics tracking for Xamarin iOS, and you may save another developer’s time as well… 😉

Cheers ! Stay Awesome ^_^ !