迅速拨打一个电话号码

我试着拨打一个号码,不是用特定的号码,而是一个在变量中被调用的号码,或者至少告诉它把你手机里的号码调出来。在变量中调用的这个数字是我通过使用解析器或从网站 sql 中获取的数字。我做了一个按钮,试图调用电话号码存储在一个函数的变量,但无济于事。什么都行,谢谢!

    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)!)


}
142867 次浏览

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

Okay I got help and figured it out. Also I put in a nice little alert system just in case the phone number is not valid. My issue was I was calling it right but the number had spaces and unwanted characters such as ("123 456-7890"). UIApplication only works or accepts if your number is ("1234567890"). So you basically remove the space and invalid characters by making a new variable to pull only the numbers. Then calls those numbers with the UIApplication.

func callSellerPressed (sender: UIButton!){
var newPhone = ""


for (var i = 0; i < countElements(busPhone); i++){


var current:Int = i
switch (busPhone[i]){
case "0","1","2","3","4","5","6","7","8","9" : newPhone = newPhone + String(busPhone[i])
default : println("Removed invalid character.")
}
}


if  (busPhone.utf16Count > 1){


UIApplication.sharedApplication().openURL(NSURL(string: "tel://" + newPhone)!)
}
else{
let alert = UIAlertView()
alert.title = "Sorry!"
alert.message = "Phone number is not available for this business"
alert.addButtonWithTitle("Ok")
alert.show()
}
}

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.

This is an update to @Tom's answer using Swift 2.0 Note - This is the whole CallComposer class I am using.

class CallComposer: NSObject {


var editedPhoneNumber = ""


func call(phoneNumber: String) -> Bool {


if phoneNumber != "" {


for i in number.characters {


switch (i){
case "0","1","2","3","4","5","6","7","8","9" : editedPhoneNumber = editedPhoneNumber + String(i)
default : print("Removed invalid character.")
}
}


let phone = "tel://" + editedPhoneNumber
let url = NSURL(string: phone)
if let url = url {
UIApplication.sharedApplication().openURL(url)
} else {
print("There was an error")
}
} else {
return false
}


return true
}
}

I am using this method in my application and it's working fine. I hope this may help you too.

func makeCall(phone: String) {
let formatedNumber = phone.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
let phoneUrl = "tel://\(formatedNumber)"
let url:NSURL = NSURL(string: phoneUrl)!
UIApplication.sharedApplication().openURL(url)
}

Swift 3.0 solution:

let formatedNumber = phone.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
print("calling \(formatedNumber)")
let phoneUrl = "tel://\(formatedNumber)"
let url:URL = URL(string: phoneUrl)!
UIApplication.shared.openURL(url)

In Swift 3,

if let url = URL(string:"tel://\(phoneNumber)"), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}

The above answers are partially correct, but with "tel://" there is only one issue. After the call has ended, it will return to the homescreen, not to our app. So better to use "telprompt://", it will return to the app.

var url:NSURL = NSURL(string: "telprompt://1234567891")!
UIApplication.sharedApplication().openURL(url)

openURL() has been deprecated in iOS 10. Here is the new syntax:

if let url = URL(string: "tel://\(busPhone)") {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

Swift 3.0 and ios 10 or older

func phone(phoneNum: String) {
if let url = URL(string: "tel://\(phoneNum)") {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url as URL)
}
}
}

Here's an alternative way to reduce a phone number to valid components using a Scanner

let number = "+123 456-7890"


let scanner = Scanner(string: number)


let validCharacters = CharacterSet.decimalDigits
let startCharacters = validCharacters.union(CharacterSet(charactersIn: "+#"))


var digits: NSString?
var validNumber = ""
while !scanner.isAtEnd {
if scanner.scanLocation == 0 {
scanner.scanCharacters(from: startCharacters, into: &digits)
} else {
scanner.scanCharacters(from: validCharacters, into: &digits)
}


scanner.scanUpToCharacters(from: validCharacters, into: nil)
if let digits = digits as? String {
validNumber.append(digits)
}
}


print(validNumber)


// +1234567890

I am using swift 3 solution with number validation

var validPhoneNumber = ""
phoneNumber.characters.forEach {(character) in
switch character {
case "0"..."9":
validPhoneNumber.characters.append(character)
default:
break
}
}


if UIApplication.shared.canOpenURL(URL(string: "tel://\(validNumber)")!){
UIApplication.shared.openURL(URL(string: "tel://\(validNumber)")!)
}

Swift 3.0 & iOS 10+

UIApplication.shared.openURL(url) was changed to UIApplication.shared.open(_ url: URL, options:[:], completionHandler completion: nil)

options and completion handler are optional, rendering:

UIApplication.shared.open(url)

https://developer.apple.com/reference/uikit/uiapplication/1648685-open

Swift 3, iOS 10

func call(phoneNumber:String) {
let cleanPhoneNumber = phoneNumber.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
let urlString:String = "tel://\(cleanPhoneNumber)"
if let phoneCallURL = URL(string: urlString) {
if (UIApplication.shared.canOpenURL(phoneCallURL)) {
UIApplication.shared.open(phoneCallURL, options: [:], completionHandler: nil)
}
}
}

For a Swift 3.1 & backwards compatible approach, do this:

@IBAction func phoneNumberButtonTouched(_ sender: Any) {
if let number = place?.phoneNumber {
makeCall(phoneNumber: number)
}
}


func makeCall(phoneNumber: String) {
let formattedNumber = phoneNumber.components(separatedBy:
NSCharacterSet.decimalDigits.inverted).joined(separator: "")


let phoneUrl = "tel://\(formattedNumber)"
let url:NSURL = NSURL(string: phoneUrl)!


if #available(iOS 10, *) {
UIApplication.shared.open(url as URL, options: [:], completionHandler:
nil)
} else {
UIApplication.shared.openURL(url as URL)
}
}

For swift 3.0

if let url = URL(string: "tel://\(number)"), UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
else {
print("Your device doesn't support this feature.")
}

If your phone number contains spaces, remove them first! Then you can use the accepted answer's solution.

let numbersOnly = busPhone.replacingOccurrences(of: " ", with: "")


if let url = URL(string: "tel://\(numbersOnly)"), UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}

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)


}
}
}
}

For Swift 4.2 and above

if let phoneCallURL = URL(string: "tel://\(01234567)"), UIApplication.shared.canOpenURL(phoneCallURL)
{
UIApplication.shared.open(phoneCallURL, options: [:], completionHandler: nil)
}
let formatedNumber = phone.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
print("calling \(formatedNumber)")
let phoneUrl = "tel://\(formatedNumber)"
let url:URL = URL(string: phoneUrl)!
UIApplication.shared.openURL(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)
}

Many of the other answers don't work for Swift 5. Below is the code update to Swift 5:

let formattedNumber = phoneNumberVariable.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")


if let url = NSURL(string: ("tel:" + (formattedNumber)!)) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url as URL)
}
}

PS:

  1. With most of the answers, I wasn't able to get the prompt on the device. The above code was successfully able to display the prompt.
  2. There is no // after tel: like most answers have. And it works fine.
func phone(phoneNum: String) {
if let url = URL(string: "tel://\(phoneNum)") {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url as URL)
}
}
}

For iOS 10 and above use below code to make a call

let phoneNo = "1234567890"
guard let number = URL(string: "tel://" + phoneNo ) else { return}
UIApplication.shared.open(number, options: [:], completionHandler: nil)