Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a phonecall ios xamarin

I currently have a button in a table view. I have a custom cell class and an update cell method.

public void UpdateCell (string subtitle2)
{               
    call.SetTitle(subtitle2, UIControlState.Normal);
    call.TouchUpInside += (object sender, EventArgs e) => {
        UIApplication.SharedApplication.OpenUrl(new NSUrl("tel:" + subtitle2));
    };          
}

However, when i run this segment of code, i get an error.

Could not initialize an instance of the type 'MonoTouch.Foundation.NSUrl': the native 'initWithString:' method returned nil. It is possible to ignore this condition by setting MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure to false.

like image 202
user3748957 Avatar asked Dec 15 '22 20:12

user3748957


2 Answers

Try this:

public void UpdateCell (string subtitle2)
{
    //Makes a new NSUrl
    var callURL = new NSUrl("tel:" + subtitle2);

    call.SetTitle(subtitle2, UIControlState.Normal);
    call.TouchUpInside += (object sender, EventArgs e) => {
    if (UIApplication.SharedApplication.CanOpenUrl (callURL)) {
    //After checking if phone can open NSUrl, it either opens the URL or outputs to the console.

        UIApplication.SharedApplication.OpenUrl(callURL);
    } else {
    //OUTPUT to console

    Console.WriteLine("Can't make call");
    }
  };          
}

Not sure if phone calls can be simulated in the iPhone Simulator, otherwise just connect your device :-)

like image 151
Emil Elkjær Avatar answered Dec 17 '22 10:12

Emil Elkjær


As mentioned in other answers, NSUrl cannot handle spaces (and some other symbols) in URL string. That symbols should be encoded before passing to the NSUrl constructor. You can do the encoding with the NSString.CreateStringByAddingPercentEscapes method. Another way is using of the .NET Uri class:

new NSUrl(new Uri("tel:" + subtitle2).AbsoluteUri)

The issue you might encounter here is parsing of the schema by the Uri class. To avoid it, don't use ://, so, URL strings should look as "tel:(123) 345-7890", not as "tel://(123) 345-7890"

like image 42
Eugene Berdnikov Avatar answered Dec 17 '22 11:12

Eugene Berdnikov