I'm trying to call a number not using specific numbers but a number that is being called in a variable or at least tell it to pull up the number in your phone. This number that is being called in a variable is a number that I retrieved by using a parser or grabbing from a website sql. I made a button trying to call the phone number stored in the variable with a function but to no avail. Anything will help thanks!
func callSellerPressed (sender: UIButton!){
//(This is calls a specific number)UIApplication.sharedApplication().openURL(NSURL(string: "tel://######")!)
// This is the code I'm using but its not working
UIApplication.sharedApplication().openURL(NSURL(scheme: NSString(), host: "tel://", path: busPhone)!)
}
Create a UIButton in the Interface Builder. Link that button's IBAction into a swift file. Inside that swift function, create a URL object with the tel:// string. Open that URL string you created when the user presses the button.
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)
}
}
}
}
Swift 5: iOS >= 10.0
This solution is nil save.
Only works on physical device.
private func callNumber(phoneNumber: String) {
guard let url = URL(string: "telprompt://\(phoneNumber)"),
UIApplication.shared.canOpenURL(url) else {
return
}
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With