vimeo in xamarin ios app

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!😀

I am a Developer and I Code with ‪#‎VisualStudio‬ ! ;)

I code with Visual Studio 2

I am a Developer and I Code with #VisualStudio.😀 Build your own Visual Studio profile today at aka.ms/myVisualStudio!
Yep that’s me, that hyper-active kid in the photo lol😛
Kudos to whoever created this simply awesome tool.😀
– Udara Alwis
[ÇøŋfuzëРSøurcëÇødë]
microsoft xamarin

So I gave a Tech Talk at Dot Net Developers Meetup, Singapore hosted by Microsoft…

Yeei!😀 I got an awesome opportunity present a tech talk at Dot Net Developers Meetup in Singapore which was hosted by Microsoft. This happened to be my first ever Presentation on Xamarin, and yeah it was totally awesome. A great enthusiastic crowd and everything went pretty well..:)

Thank you so much for the Organizers and Microsoft for this incredible opportunity, and I’m truly humbled by it.

There I spoke about Xamarin and Xamarin Forms, Xamarin UI Rendering process, Overriding this process through Custom Renderers, and important facts to keep in mind when implementing Custom Renderers in Xamarin Forms.

So I thought of putting out a small article on the Summary of this tech talk on my blog.😀

Xamarin Forms Custom Renderers for the Rescue…

Here’s the slideshow I used during this talk…

Xamarin is…

Xamarin is truly a great platform. It let’s you create mobile applications using C# dot net having full Native Performance as well as Looks and Feels of each Native Platform.

Xamarin Forms Custom Renderers for the Rescue.004

As you can see in the diagram, thanks to Xamarin now we can maintain the same code base across all three mobile platforms, having the individual native UI implementation, which allows us to maintain up to about 70% percent shared codebase. So yeah its all Great.

Xamarin Forms is…

Xamarin Forms, in one single word, is awesome! Its more like the cross platform extension of Xamarin this is the component which brings to life of the concept, Write once, Run Everywhere, and not Suck allowing us to share the UI code layer among three platforms. So you no longer need to implement the UI separately for each platform.

Xamarin Forms Custom Renderers for the Rescue.005

Xamarin and Xamarin Forms ?

Some people are confused about these differentiation between Xamarin and Xamarin Forms, let me put it this way…

Xamarin Forms Custom Renderers for the Rescue.006

Xamarin Forms is more like the true cross platform extention of Xamarin. Where as Xamarin Forms provides us a unified UI Layer which has all the common UI controls (Layouts, Labels, TextBoxes, Buttons, etc…) of all three mobile platforms, with almost every single common property of those controls.

Still Confused ? Let me explain…

Xamarin Forms Custom Renderers for the Rescue.007

In your left hand side you can see the Native Xamarin architecture where you share the back-end code base, but you have to implement the UI separately for each platoform, allowing us to share upto 70-80% of code base.

Where as in Xamarin Forms you can share almost upto 100% of the code base across all three platforms with the Shared UI Layer.

A little Story about a fresh Xamarin Forms developer…

There’s this developer who started developing an application with Xamarin forms, where he’s given all the UI sketches and so on.

Xamarin Forms Custom Renderers for the Rescue.008

So he start off with default nice and simple controls in Xamarin Forms and manages to implement the basic UI design of the app. Then he slowly gets into complex UI designs implementations…

So he starts going through all the available properties in these Xamarin Forms Controls, and begins to wonder where are all the properties that he needs to be using in order to customize the app accordingly to the complex design.

So he looks up and down, here and there, wondering where did all the properties go?

Oh boy, he’s in trouble, isn’t he… He realise Xamarin Forms UI controls has limited set of properties for customization, and its very hard to do complex customization in these controls.

Any Solutions ?

Any solutions ? Well he could always go back to native development, but its late for it now, and it’ll put him through a lot of trouble for sure, having to implement in three platforms.

Now that’s where Xamarin Forms Custom Renderers comes in for the rescue, let me explain.

Xamarin Forms Custom Renderers for the Rescue.010

Xamarin Forms UI Rendering process…

Each and every UI Control in Xamarin Forms has it’s own Native Renderer which renders and maps its Properties and Behaviours to the Native Control level.

So yeah behold the Magic of Xamarin Forms, this happens accordingly to the Native Platforms. This is why we get the Native look and feel and performance with Xamarin Forms.

Xamarin Forms Custom Renderers for the Rescue.011

Take a look at the Diagram here it shows how the default texbox UI Control of Xamarin Forms, which is called “Entry” control gets rendered down to the Native level through the Renderers. Now focus down through the iOS rendering, where the Entry control gets rendered down to the native UITextField control. And on Android and Windows Phone, EditText and UserControl respectively.

Overriding this Rendering Process ?

Xamarin has allowed us to access this Rendering process, which in return allows us to Override this default process and use it for our own requirements.

Xamarin Forms Custom Renderers for the Rescue.012

So by accessing this process we can customize all kinds of properties and behaviours of the Xamarin Forms controls, in each platform according to our needs.

Xamarin Forms Custom Renderers…

So in order to access this rendering process we need to create Custom Renderers of our own by sub classing the base Renderers Xamarin provides. Thereby it allows us to access and modify the native level properties and behaviours of the Xamarin Forms Controls.

Xamarin Forms Custom Renderers for the Rescue.013

Take a look at the Diagram above, that’s how Custom Renderers gets involved in the Rendering process, where as the Xamarin Forms Entry control goes through the Custom Renderer and down to the base renderer, where we control and modify its properties and behaviours in our Custom Renderer as we need.

How to create Xamarin Forms Custom Renderers ?

Just 3 simple steps…

  1. First you create a Custom Control by subclassing the default Xamarin Forms Control that you need to create a Custom Renderer for.
  2. Second you consume that subclassed Custom Control in your Xamarin Forms application.
  3. Thirdly and finally, you implement the Custom Renderer in the Native levels project.

Yeah how hard could it be, just three simple steps!😉

Here’s a Simple Custom Renderer Demo on the house…

Check out the live demo Custom Renderer I implemented during this presentation on my Github from below, https://github.com/UdaraAlwis/XFCircleCornersButtonControlDemo

Important facts to consider WHEN implementing Custom Renderers…

So here are some important facts to keep in mind when you implement Custom Renderers in Xamarin Forms, so that you get a good understanding about how to implement a custom renderer and what to keep in mind…

1. Always Export your Custom Renderers…

Whenever you create a custom renderer you need to Export it and register it, otherwise Xamarin would not recognise your Custom Renderer and it will go ahead with the default base class Renderer for your Custom Control.

Capture

2. Overriding the OnElementChanged Method…

Whenever a Custom Renderer is being execute, the first method it fires is the OnElementChanged() method.

This method gets called when the Rendering process starts for the custom control, which allows us the opportunity to to tap into the native properties and behaviours and modify them as we wish by overriding this method.

Also something to keep in mind this method consumes an important parameter, ElementChangedEventArgs which contains two important Properties.

  1. The OldElement property represents the Xamarin Forms level Control this renderer was attached to (previously attached to) and
  2. The NewElement property represents the Xamarin Forms level Control this renderer is currently attached to, its more of a reference.

So if you are using any Event Handlers in your Custom Renderer, you have to keep an eye out for these two properties in order to Subscribe and Unsubscribe accordingly to prevent memory leaks.

Capture1

3. Control vs Element Property…

If you think about it, Custom Renderer is more like a middle guy, in between Xamarin Forms level Control and the Native level Control, where as it’s got hooks for both levels.

So those hooks are represented by these two important properties, Control and Element.

Element property, it holds a reference to the Xamarin.Forms control that’s being rendered, so you could use this property to access anything on the Xamarin Forms level of the custom control, such as Text, WidthRequest, HeightRequest and so on.

Control property holds a reference to the Native Control being used of the Custom Control. So using this property you can straight away add your native customisations and behaviours to the Rendering Control.

3. Overriding the whole Native Control ?

What if you want to get rid of the default Native Control associated with your Custom Renderer ? Create your own Native Control and use it for your Custom Control ?

As an example You need to have a TextBox with an underneath shadow, in iOS you can’t do this with the default native UITextView, so one way to do it is by adding another UIView along with the UITextView, where as you merge two native views together to form one View.

So for instances like that, you could use the SetNativeControl() method, and pass in your custom native view, which will get rid of the default native view and override it with your custom native view.

But you have to keep in mind something very important, hence you are flushing away the default native control, you have to handle all the Behaviours (Events) of your own Native Control manually by yourself and map it back and forth with the Xamarin Forms level.

4. Creating your own Base Renderer…

For every Xamarin Forms Control, there is a Base Renderer, that maps it to the Native Level and we use those Base Renderers all the time such as Button Renderer, Label Renderer and so on.

Now what if you wanted to create your own Base Renderer ? Let’s say you are creating a total complex Custom Control by yourself, and you need to have your own Renderer for it?

YES! it is possible, you just simply have to derive your Base Renderer from the generic ViewRenderer<?,?> where as you have to pass in your Custom Renderer type name and the associating Native Control type name for the renderer.

Well actually Xamarin doesn’t really recommend this, there some instance that you need to move towards this approach.

Let me Share some Wisdom…

Xamarin Forms Custom Renderers for the Rescue.022

Here’s something interesting I really want share with your all is that, Xamarin doesn’t really require in depth Mobile Development knowledge but it is very beneficial to have some, specially in scenarios like these Custom Renderer implementation. The more you are aware of the Native development, the more advantages for you.

So if you are planning to move towards Xamarin mobile development, I would suggest you take a little look at native development as well… Which will prepare you better for your Xamarin Mobile Development journey.

Important facts to consider BEFORE implementing Custom Renderers…

Earlier I mentioned about the facts that you need to keep in mind when you implement Custom Renderers, now let’s see what are the facts you need to focus BEFORE you decide to implement Custom Renderers in your application.

 

1. Think twice…

You need to think twice before you move on towards Custom Renderer implementation for your Application. Once you get familiar with Custom Renderer implementation, you get very tempted to go for custom renderers all the time even for the simplest requirement, but trust me it is not a good practice at all.

Why I say this is because, and untold truth about Custom Renderers is that, they are a little process intensive.

Therefore it’s wise to first of all explore all the possible solutions you could come up with from Xamarin Forms level it self to solve your requirement. So do not over-use Custom Renderers just because of the ease of development.

You could also try out other alternatives such as,

  1. Xamarin Forms Controls sub-classing and forming Custom Control (by merging multiple Controls to create a new Control).
  2. Xamarin Forms Effects (which is almost like Custom Renderers but simplified).

 

2. Re-usability…

Whenever you decide to implement a Custom Renderer You need to pay attention to the reusability of it. Make sure to implement it in a way its reusable as much as possible.

When ever you implement Custom Renderers, don’t only focus on the current implementation, think ahead and implement all the possible needs in one go, without implementing custom renderers for every single need from one type of control.

Since Custom renderers are process intensive it very important to focus on reusability.

3. Mapping of Xamarin Forms -> Native Level…

Last but not least before you implement your Custom Renderer always make sure to take a look down through your Rendering Hierarchy…

Xamarin Forms Custom Renderers for the Rescue.026

Look at the available Properties and Behaviours down to the Native control and see whether it actually fulfils your requirements, in all three platforms (Android, iOS, Windows Phone). That way you will have a better idea on how to implement the Custom renderer more efficiently.

Conclusion…

Xamarin Forms Custom Renderers for the Rescue.028

Custom Renderers plays an extremely important role in Xamarin Forms development. In my opinion it’s more like the Magic behind the whole Xamarin Forms Awesomeness.

Don’t be scared of Custom Renderer’s because they are here for your rescue.

Also finally make sure to keep in mind all the important tid bits I discussed today, so it will help you implement custom renderers more efficiently and effectively.:)

AAAANND THAT BROUGHT US TO THE END OF THE PRESENTATION! Hope this was helpful for anyone missed this session and keep in touch everyone!😀

Once again Thanks for the Organisers for organising this event and Microsoft for hosting. As well as the enthusiastic crowd.:)

– Udara Alwis
CODENAME: [ÇøŋfuzëРSøurcëÇødë]

https://www.linkedin.com/in/udaraalwis

https://www.facebook.com/confuzed.sourcecode

Untitled-1

Handling Page Transition Animations in Xamarin Android

Alright let’s get straight to point, You want to add some fancy transition animations to your Pages in your Xamarin Android app ? more specifically when the user navigates through the app between the pages, you need to add some nice animations for the page transition ?😉

I came across this situation and I couldn’t find any articles on it, therefore after solving my issue, I decided to write my own to share my experience.

Yep here’s how you do it in Xamarin Android..😉

In Android we could define the type of transition animation that we need to add to our pages, both when we are opening the page and exiting the page, whereas we could pass those defined properties to the page Activity included in the Bundle object.😀

So that’s what we are going to do.

As you can see below I have created a custom animation for the page MyPageActivity whereas this certain page would use the defined animations when during it’s opening and exiting executions.

We define the animation and include them in a bundle to pass into the StartActivity method, in order to deliver it to the opening Activity.

// Adding the transition animation to the ActivityOptions and include them in a Bundle
Bundle animationBundle = ActivityOptions.MakeCustomAnimation(this, Resource.Animation.abc_fade_in, Resource.Animation.abc_fade_out).ToBundle();

// Pass on the Bundle object to the StartActivity method 
this.StartActivity(new Intent(this, typeof(MyPageActivity)), animationBundle);

 

Above I have created the animation using the existing default animation types, you could add your own custom animations as you wish just as above, whereas you just have to give the resource ID for the custom animation of your’s.:)

Well, hope that was helpful…:)

Sorry this was a short post without any screenshots, going through some crazy busy times at office, barely having any time to blog😦

Cheers! Stay Awesome!😀

 

Untitled-1

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!😀

Xamarin Motivation #01

 

WE ARE NEW

YOU DON’T HAVE TO HAVE AN IN DEPTH KNOWLEDGE IN ANDROI / IOS / WINPHONE DEVELOPMENT TO START OFF WITH XAMARIN… BUT YOU WILL END UP WITH AN IN DEPTH KNOWLEDGE OF MOBILE DEVELOPMENT ONCE YOU’RE DONE WITH XAMARIN….

– ÇøŋfuzëÐ SøurcëÇødë [Udara Alwis]

Untitled-1

So I created this AwesomeHyperLinkLabel custom renderer control one day for Xamarin Forms!

Have you ever wanted to create a Label that could automatically detect HTTP Web Links ? or Phone number text ? or EMail address text ? and enable clickable action only on top of those links in the Label ?😉

Well it’s a very common scenario in Mobile Apps development, if you had experienced it already, you know its very easy in Native app development. But when it comes to Xamarin Forms, oh well it’s a different story, whereas people almost end up trying to implement a WebView control instead of the Label and complicate the whole situation. lol😀 (Yes I have been there too) Well XFLabs have a clickable Label control, but who on earth would want to make an entire Label control clickable only for a specific set of text like an email address inside a label, unless your intension is to fill the whole label with the email address only.😛

Anyhow there was this one time I wanted to create a Label which automatically detect HTTP Web URLs, Phone Number text, Email Address text and enables clickable actions only on top of those specific types of text.

Solution ?

Well if it’s impossible to do it in Xamarin Forms, of course we need to praise the Custom Renderers, just like I did in my scenario. So here goes my solution. We are going to create a Custom Control in Xamarin Forms, which is going to be overridden in native Level and adjust the control to our needs. And I’m gonna call it the “AwesomeHyperLinkLabel

PCL Implementation

So as usual, we create a custom control based on the Xamarin Forms Label as shown below…

namespace WhateverYourNamespace
{
    /// <summary>
    /// Automatically detects the Phone numbers, web links and email addresses
    /// and make them clickable to be opened up in default device applications
    /// </summary>
    public class AwesomeHyperLinkLabel : Label
    {

    }
}

 

Android Implementation

In Android we have the option property in default TextView called AutoLinkMask , which allows us to automatically set the TextView to detect and highlight all kinds of URLs, Phone Numbers, and EMail addresses.

[assembly: ExportRenderer(typeof(AwesomeHyperLinkLabel), typeof(AwesomeHyperLinkLabelRenderer))]
namespace WhateverYourNamespace
{
    public class AwesomeHyperLinkLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            var view = (AwesomeHyperLinkLabel)Element;
            if (view == null) return;

            TextView textView = new TextView(Forms.Context);
            textView.LayoutParameters = new LayoutParams(LayoutParams.WrapContent, LayoutParams.WrapContent);
            textView.SetTextColor(view.TextColor.ToAndroid());
            
	    // Setting the auto link mask to capture all types of link-able data
            textView.AutoLinkMask = MatchOptions.All;
	    // Make sure to set text after setting the mask
            textView.Text = view.Text;
            textView.SetTextSize(ComplexUnitType.Dip, (float)view.FontSize);

	    // overriding Xamarin Forms Label and replace with our native control
            SetNativeControl(textView);
        }
    }
}

 

So as you can see above I have overridden the Xamarin Forms control with our native TextView control. Make sure to set text after setting the AutoLinkMask, otherwise the link-able text would not be detected by the TextView. Also keep in mind here you could define specifically what types of link-able data you need the Label to detect based on your requirements.😉 but above example I have set it to all.

iOS Implementation

Also in iOS, we could use DataDetectorTypes property on UITextView which allows us to do the same as above, but keep in mind in Xamarin iOS UILabel is the equivalent of Xamarin Forms Label, but UILabel doesn’t have such properties to support our scenario. So we have to move to the native UITextView control.

It’s very important to keep in mind due to the above reasons we cannot derive this Custom Renderer from the usual LabelRenderer, we need to use the common ViewRenderer.

[assembly: ExportRenderer(typeof(AwesomeHyperLinkLabel), typeof(AwesomeHyperLinkLabelRenderer))]
namespace WhateverYourNamespace
{
    public class AwesomeHyperLinkLabelRenderer : ViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<View> e)
        {
            base.OnElementChanged(e);

            var view = (AwesomeHyperLinkLabel)Element;
            if (view == null) return;

            UITextView uilabelleftside = new UITextView(new CGRect(0, 0, view.Width, view.Height));
            uilabelleftside.Text = view.Text;
            uilabelleftside.Font = UIFont.SystemFontOfSize((float)view.FontSize);
            uilabelleftside.Editable = false;
			
	    // Setting the data detector types mask to capture all types of link-able data
            uilabelleftside.DataDetectorTypes = UIDataDetectorType.All;
            uilabelleftside.BackgroundColor = UIColor.Clear;

	    // overriding Xamarin Forms Label and replace with our native control
            SetNativeControl(uilabelleftside);
        }
    }
}

 

So as you can see above we are setting the DataDetectorTypes property in UITextView to allow the control to highlight the link-able data. Also specially note that we are using ViewRenderer and overriding the Xamarin Forms Label with UITextView control.

That is why we have disabled the Editable property above and we are doing our best for this control to behave as a Label.

Let’s try it out!

Too bored to try it out yourself ?😛 Yeah thought so. lol Anyways here’s a sample code where you could try out my AwesomeHyperLinkLabel.

public App()
{
	// The root page of your application
	MainPage = new ContentPage
	{
		Content = new StackLayout
		{
			VerticalOptions = LayoutOptions.Center,
			Padding = new Thickness(10, 0, 10, 0),
			Children = {
				new Label
				{
					Text = "Hello! This is normal Label!"
				},
				new AwesomeHyperLinkLabel {
					Text = "Hello! This is the AwesomeHyperLinkLabel by ÇøŋfuzëÐ SøurcëÇødë ! \n\nClick here www.confuzed-sourcecode.com and phone number : +65 9215 7231 and email address : udara.blahblah@blah.com"
				},
			}
		}
	};
}

 

Very well, there you go fellas, now hit F5 and run that thing…😉

TADAAAA!

WOOT WOOT ! Here how it is in iOS and Android !😀

Simulator Screen Shot 8 Mar 2016, 2.09.12 PM Nexus 4 (Lollipop) Screenshot 1

Cheers!

Stay awesome fellas!:)

 

webview nav

How to handle Xamarin Forms WebView internal Navigations!

So you put a Webpage or some HTML content inside your Xamarin Forms WebView ? Specially with Hyperlinks? Or basically you loaded a whole Website inside the WebView?  And now you are worried you can’t control or monitor the Navigation inside the WebView with all those Hyperlink clicks?

Situation…

Oh well I have been in the same situation, where I basically loaded a WebPage and then I wanted to control and monitor it’s internal HyperLink clicks. We already know that the Xamarin Forms WebView doesn’t come with a lot of control properties, but lucky enough they have wrapped the Navigating event of the WebView which could help us Control/Monitor the Hyperlink clicks/navigations inside the Xamarin Forms WebView.

So this is how you do it…

It’s pretty easy actually, but a lot of developers miss this event when it comes to the Xamarin Forms WebView. We can easily subscribe to the Navigating event of the WebView, whereas whenever the user clicks on any HyperLink inside the WebView the action goes through this event, thereby allowing us to monitor and control the hyperlink click of the WebView.

Inside the Navigating Event we have the access to the Event parameter, which let’s us access what the HyperLink that the user clicked on, and as you can see in the below code, I have checked what’s the HyperLink user clicked on and based on that URL string, I’m executing my custom action.

Also keep in mind this allows you to even Cancel that certain HyperLink click event, once you execute your own overridden process as you can see below.

mywebView.Navigating += (s, e) =>
{
	if (e.Url.StartsWith("https://www.whateverlink112312.com.sg/"))
	{
		// now do this instead of navigating within the WebView...
		//....
		//....
		// and finally cancle the defauly WebView Navigation...
		e.Cancel = true;
	}
	else if (e.Url.StartsWith("https://www.whateverlink4444.com.sg/"))
	{
		// now do this instead of navigating within the WebView...
		//....
		//....
		// and finally cancle the defauly WebView Navigation...

		e.Cancel = true;
	}
	else if (e.Url.StartsWith("https://www.whateverlink333333.com.sg/"))
	{
		// now do this instead of navigating within the WebView...
		//....
		//....
		// and finally cancle the defauly WebView Navigation...

		e.Cancel = true;
	}
};

 

So just like that you can gain access to the entire HyperLink click event and control or monitor it in anyways as you wish. For example different actions for different types of HyperLink clicks.😉

There you go fellas!😀

Stay Awesome!😉

transparent webview

Alright, let’s make a Transparent Xamarin Forms Webview!

Have you ever wanted to add a WebView to your Xamarin Forms app and make it’s background transparent ? Let’s say you need to display some custom Text Label’s or some custom control with loads of customization to it’s content or sub controls ?
Whereas your first solution would be to go for a WebView control, but you need to make that WebView Transparent to match the background color of the page ? If you had gone through or going through such requirements, then this article is for you.

WebView for Fancy Stuff…

We all know WebView is usually used for displaying Web Content right ? but then also we could use it to display complicated customized text or content, but then there is one problem, matching the Page background to the WebView control, because it’s impossible to set the background transparent of the WebView in Xamarin Forms.

Solution ?

Yeah you guess right! Custom Renderers for the RESCUE! WOOT!

So here is how I implemented my Transparent WebView with life-saving Custom Renderers in Xamarin Forms.

PCL implementation

So as usual we need to sub-class the default Xamarin Forms WebView control with our Transparent WebView control as follows.

namespace TransparentWebViewXamForms
{
    /// <summary>
    /// Subclassing our Transparent WebView from 
    /// the default Xamarin Forms WebView control
    /// </summary>
    public class TransparentWebView : WebView
    {

    }
}

 

Android implementation

So as of our Android implementation we need to access the native control counterpart for the Xamarin Forms WebView using the WebViewRenderer.

[assembly: ExportRenderer(typeof(TransparentWebView), typeof(TransparentWebViewRenderer))]
namespace TransparentWebViewXF.Droid
{
    public class TransparentWebViewRenderer : WebViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
        {
            base.OnElementChanged(e);

            // Setting the background as transparent
            this.Control.SetBackgroundColor(Android.Graphics.Color.Transparent);
        }
    }
}

 

We access the Control property which holds the native Android WebView control which deals with the Xamarin Forms WebView. As you can see above we set the Control Background color to Transparent through SetBackgroundColor() method. BOOM! You are good to go with Android!

iOS implementation

Now let’s dive into iOS, well its the same as Android, the trick is to set the Control’s background color to Transparent.

[assembly: ExportRenderer(typeof(TransparentWebView), typeof(TransparentWebViewRenderer))]
namespace TransparentWebViewXF.iOS
{
    public class TransparentWebViewRenderer : WebViewRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
			
	    // Setting the background as transparent
            this.Opaque = false;
            this.BackgroundColor = Color.Transparent.ToUIColor();
        }
    }
}

 

But also we need to set the Opaque property to false as show above, otherwise the control wouldn’t render as transparent. Then as usual we set the BackgroundColor property.

So let’s try it out!

Too lazy to try it out ?😛 No worry, I would probably be bored to try it out unless I actually need to. haha.

So here goes the sample implementation, if you have implemented the above properly, then use the below test code and run your app!

You can see below, I’m setting the Page’s background color to Red and the StackLayout’s background color to Yellow. Now the WebView should be rendered as Transparent and the Yellow background should be visible.:)

MainPage = new ContentPage
{
	BackgroundColor = Color.Red,

	Content = new StackLayout
	{
		BackgroundColor = Color.Yellow,
		VerticalOptions = LayoutOptions.CenterAndExpand,
		Children = {
			new Label {
				XAlign = TextAlignment.Center,
				TextColor = Color.Red,
				FontSize = 20,
				Text = "Welcome to Xamarin Forms!"
			},

			new TransparentWebView() { 
				Source = new HtmlWebViewSource()
				{
					Html = @"<html><body>
						<center>
						<h1>Awesome Transparent WebView!</h1>
						<p>by ÇøŋfuzëÐ SøurcëÇødë</p>
						<br> call us : <a href='tel:+6576216231'>1-847-555-5555</a>
						<br> email us : <a href='mailto:webmaster@example.com'>blah@blah.com</a>
						<br> visit us : <a href='http://www.awesome.com'>Awesome.com</a>
						</center>
						</body></html>",
				},
				HeightRequest = 400
			},

			new Label {
				XAlign = TextAlignment.Center,
				TextColor = Color.Red,
				FontSize = 20,
				Text = "And that's the end of it! Have fun!"
			},
		}
	}
};

 

BOOM! THERE YOU GO!😀

Simulator Screen Shot 2 Mar 2016, 10.23.43 PM Nexus 4 (Lollipop) Screenshot 1

Alright! Now go crazy with it fellas!

Stay Awesome!😉