How to use openURL for making a phone call in Swift?

user3739367 picture user3739367 · Jun 16, 2014 · Viewed 56k times · Source

I have converted the code for making a phone call from Objective-C to Swift, but in Objective-C, we can set the type of the URL that we like to open (e.g. telephone, SMS, web) like this:

@"tel:xx"
@"mailto:[email protected]"
@"http://stackoverflow.com"
@"sms:768number"

The code in Swift is:

UIApplication.sharedApplication().openURL(NSURL(string : "9809088798")

I read that have not released any scheme parameter for tel:, but I don't know if Swift can detect if the string is for making a phone call, sending email, or opening a website. Or may I write:

(string : "tel//:9809088798")

?

Answer

Lou Franco picture Lou Franco · Jun 16, 2014

I am pretty sure you want:

UIApplication.sharedApplication().openURL(NSURL(string: "tel://9809088798")!)

(note that in your question text, you put tel//:, not tel://).

NSURL's string init expects a well-formed URL. It will not turn a bunch of numbers into a telephone number. You sometimes see phone-number detection in UIWebView, but that's being done at a higher level than NSURL.

EDIT: Added ! per comment below