Jamie McAllister
Jamie McAllister

Reputation: 729

How to make a phone call with Swift 3?

I'm building an app for a business and I've run into a dead end. I need a button that will start a phone call to a client's mobile number.

I have this, which is how it should work in Swift 2:

@IBAction func clientMobile(_ sender: AnyObject) {
    UIApplication.shared.openURL(self.mobile!)
}

However openURL is deprecated and I don't see any alternative in the intellisense. What is the Swift 3 equivalent of the above line of code?

One other thing, when I run this code I have thee following error:

 fatal error: unexpectedly found nil while unwrapping an Optional value

I know the error is related to self.mobile but I'm not sure how to fix it.

Declarations and extra information:

self.mobileis declared and initialised like this:

var mobile : URL?
//inside view will appear
self.mobile = URL(string: "telprompt://" + (self.dog?.client?.mobile)!)

Upvotes: 2

Views: 5157

Answers (3)

Imtee
Imtee

Reputation: 1393

you much check iOS version
guard let number = URL(string: "telprompt://123456789") else { return }
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(number)
    } else {
        // Fallback on earlier versions
        UIApplication.shared.openURL(number)
    }

Upvotes: 3

Ignacio Inglese
Ignacio Inglese

Reputation: 2605

From the looks of it, you should be checking dog.client.mobile for some invalid characters in the phone number, or even nil (I can't tell if mobile is really optional there, if so you should check for nil before even attempting to launch the call).

Looks like your URL is coming back as nil, and you're trying to pass that to your openURL.

Your phone number should be free of symbols such as ()+-. You can easily remove those using stringByReplacingCharactersInSet (can't remember the exact name in Swift 3 right now.

Upvotes: 1

Thomm
Thomm

Reputation: 516

openURL(:) is deprecated in iOS 10.

The new method is:

- (void)openURL:(NSURL*)url options:(NSDictionary<NSString *, id> *)options

completionHandler:(void (^ __nullable)(BOOL success))completion

Example usage to support both iOS 10 and earlier versions:

// iOS10 check    
if (UIApplication.shared.respondsToSelector(#selector(UIApplication.shared.openURL(_:options:completionHandler:))) {
        UIApplication.shared.openURL(self.mobile!, options: [:], completionHandler:nil)
    } else {
        UIApplication.shared.openURL(self.mobile!)
    }

(hope this helps, sorry for any errors im on mobile atm)

Upvotes: 0

Related Questions