Calling a phone number in swift
Just try:
if let url = NSURL(string: "tel://\(busPhone)") where UIApplication.sharedApplication().canOpenURL(url) { UIApplication.sharedApplication().openURL(url)}
assuming that the phone number is in busPhone
.
NSURL
's init(string:)
returns an Optional, so by using if let
we make sure that url
is a NSURL
(and not a NSURL?
as returned by the init
).
For Swift 3:
if let url = URL(string: "tel://\(busPhone)"), UIApplication.shared.canOpenURL(url) { if #available(iOS 10, *) { UIApplication.shared.open(url) } else { UIApplication.shared.openURL(url) }}
We need to check whether we're on iOS 10 or later because:
'openURL' was deprecated in iOS 10.0
A self contained solution in iOS 10, Swift 3 :
private func callNumber(phoneNumber:String) { if let phoneCallURL = URL(string: "tel://\(phoneNumber)") { let application:UIApplication = UIApplication.shared if (application.canOpenURL(phoneCallURL)) { application.open(phoneCallURL, options: [:], completionHandler: nil) } }}
You should be able to use callNumber("7178881234")
to make a call.
Swift 4,
private func callNumber(phoneNumber:String) { if let phoneCallURL = URL(string: "telprompt://\(phoneNumber)") { let application:UIApplication = UIApplication.shared if (application.canOpenURL(phoneCallURL)) { if #available(iOS 10.0, *) { application.open(phoneCallURL, options: [:], completionHandler: nil) } else { // Fallback on earlier versions application.openURL(phoneCallURL as URL) } } }}