如何使用Swift在iOS 10中拨打电话? [重复]

问题描述 投票:55回答:6

这个问题在这里已有答案:

我希望我的应用程序能够在单击按钮时调用某个数字。我试图谷歌它但是到目前为止似乎没有iOS 10(openURL已经消失)。有人能为我举个例子吗?例如:

@IBAction func callPoliceButton(_ sender: UIButton) {
    // Call the local Police department
}
ios swift swift3 ios10 phone-call
6个回答
127
投票

你可以这样打电话:

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

对于Swift 3+,您可以使用

guard let number = URL(string: "tel://" + number) else { return }
UIApplication.shared.open(number)

OR

UIApplication.shared.open(number, options: [:], completionHandler: nil)

确保您已擦除手机号码字符串以删除()-space的任何实例。


51
投票

任务

通过电话号码验证拨打电话

细节

测试:

  • Xcode 9.2,Swift 4
  • Xcode 10.2(10E125),Swift 5

extension String {

    func extractAll(type: NSTextCheckingResult.CheckingType) -> [NSTextCheckingResult] {
        var result = [NSTextCheckingResult]()
        do {
            let detector = try NSDataDetector(types: type.rawValue)
            result = detector.matches(in: self, range: NSRange(startIndex..., in: self))
        } catch { print("ERROR: \(error)") }
        return result
    }

    func to(type: NSTextCheckingResult.CheckingType) -> String? {
        let phones = extractAll(type: type).compactMap { $0.phoneNumber }
        switch phones.count {
            case 0: return nil
            case 1: return phones.first
            default: print("ERROR: Detected several phone numbers"); return nil
        }
    }

    func onlyDigits() -> String {
        let filtredUnicodeScalars = unicodeScalars.filter{CharacterSet.decimalDigits.contains($0)}
        return String(String.UnicodeScalarView(filtredUnicodeScalars))
    }

    func makeAColl() {
        guard   let number = to(type: .phoneNumber),
                let url = URL(string: "tel://\(number.onlyDigits())"),
                UIApplication.shared.canOpenURL(url) else { return }
        if #available(iOS 10, *) {
            UIApplication.shared.open(url)
        } else {
            UIApplication.shared.openURL(url)
        }
    }
}

用法

"+1-(800)-123-4567".makeAColl()

"phone:+1(617)111-22-33!".makeAColl() // Will extract "+1(617)111-22-33" and make a call

let text = "blabla, +1(222)333-44-55, dasdwedsczx acscas 123-89-01"
let phones = text.extractAll(type: .phoneNumber).compactMap { $0.phoneNumber }
print(phones)

完整样本

func test() {
    isPhone("blabla")
    isPhone("+1(222)333-44-55")
    isPhone("+42 555.123.4567")
    isPhone("+1-(800)-123-4567")
    isPhone("+7 555 1234567")
    isPhone("+7(926)1234567")
    isPhone("(926) 1234567")
    isPhone("+79261234567")
    isPhone("926 1234567")
    isPhone("9261234567")
    isPhone("1234567")
    isPhone("123-4567")
    isPhone("123-89-01")
    isPhone("495 1234567")
    isPhone("469 123 45 67")
    isPhone("8 (926) 1234567")
    isPhone("89261234567")
    isPhone("926.123.4567")
    isPhone("415-555-1234")
    isPhone("650-555-2345")
    isPhone("(416)555-3456")
    isPhone("202 555 4567")
    isPhone("4035555678")
    isPhone(" 1 416 555 9292")
    isPhone("+44 1838 300284")
    isPhone("+44 1838 300284, 1 416 555 9292")
}

private func isPhone(_ string: String) {
    let result = string.to(type: .phoneNumber) != nil
    print("\(result ? "✅" : "❌") \(string) | \(string.onlyDigits()) | \(result ? "[a phone number]" : "[not a phone number]")")
}

结果

❌ blabla |  | [not a phone number]
✅ +1(222)333-44-55 | 12223334455 | [a phone number]
✅ +42 555.123.4567 | 425551234567 | [a phone number]
✅ +1-(800)-123-4567 | 18001234567 | [a phone number]
✅ +7 555 1234567 | 75551234567 | [a phone number]
✅ +7(926)1234567 | 79261234567 | [a phone number]
✅ (926) 1234567 | 9261234567 | [a phone number]
✅ +79261234567 | 79261234567 | [a phone number]
✅ 926 1234567 | 9261234567 | [a phone number]
✅ 9261234567 | 9261234567 | [a phone number]
✅ 1234567 | 1234567 | [a phone number]
✅ 123-4567 | 1234567 | [a phone number]
✅ 123-89-01 | 1238901 | [a phone number]
✅ 495 1234567 | 4951234567 | [a phone number]
✅ 469 123 45 67 | 4691234567 | [a phone number]
✅ 8 (926) 1234567 | 89261234567 | [a phone number]
✅ 89261234567 | 89261234567 | [a phone number]
✅ 926.123.4567 | 9261234567 | [a phone number]
✅ 415-555-1234 | 4155551234 | [a phone number]
✅ 650-555-2345 | 6505552345 | [a phone number]
✅ (416)555-3456 | 4165553456 | [a phone number]
✅ 202 555 4567 | 2025554567 | [a phone number]
✅ 4035555678 | 4035555678 | [a phone number]
✅  1 416 555 9292 | 14165559292 | [a phone number]
✅ +44 1838 300284 | 441838300284 | [a phone number]
ERROR: Detected several phone numbers
❌ +44 1838 300284, 1 416 555 9292 | 44183830028414165559292 | [not a phone number]
["+1(222)333-44-55", "123-89-01"]

11
投票

针对Swift 3进行了更新:

如果您想拨打电话,请使用以下简单的代码行:

//函数定义:

func makeAPhoneCall()  {
    let url: NSURL = URL(string: "TEL://1234567890")! as NSURL
    UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
}

//函数调用:[在代码中的任何位置使用]

self.makeAPhoneCall()

注意:请在真实设备上运行该应用,因为它无法在模拟器上运行。


7
投票

在Swift 4.2中

func dialNumber(number : String) {

 if let url = URL(string: "tel://\(number)"),
   UIApplication.shared.canOpenURL(url) {
      if #available(iOS 10, *) {
        UIApplication.shared.open(url, options: [:], completionHandler:nil)
       } else {
           UIApplication.shared.openURL(url)
       }
   } else {
            // add error message here 
   }
}

如下所示

dialNumber(number: "+921111111222")

希望这有帮助。


6
投票
if let phoneCallURL:URL = URL(string: "tel:\(strPhoneNumber)") {
        let application:UIApplication = UIApplication.shared
        if (application.canOpenURL(phoneCallURL)) {
            let alertController = UIAlertController(title: "MyApp", message: "Are you sure you want to call \n\(self.strPhoneNumber)?", preferredStyle: .alert)
            let yesPressed = UIAlertAction(title: "Yes", style: .default, handler: { (action) in
                application.openURL(phoneCallURL)
            })
            let noPressed = UIAlertAction(title: "No", style: .default, handler: { (action) in

            })
            alertController.addAction(yesPressed)
            alertController.addAction(noPressed)
            present(alertController, animated: true, completion: nil)
        }
    }

6
投票

错误地我的回答是错误的,请查看这个:你可以使用这个:

guard let url = URL(string: "tel://\(yourNumber)") else {
return //be safe
}

if #available(iOS 10.0, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}

我们需要检查我们是否在iOS 10或更高版本上因为'openURL'在iOS 10.0中已被弃用

© www.soinside.com 2019 - 2024. All rights reserved.