如何使用 Swift 在 iOS 10 中拨打电话?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40078370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:35:49  来源:igfitidea点击:

How to make phone call in iOS 10 using Swift?

iosswiftswift3ios10phone-call

提问by user3175707

I want my app to be able to call a certain number when a button is clicked. I've tried to google it but there doesn't seem to have one for iOS 10 so far (where openURL is gone). Can someone put an example for me on how to do so? For instance like:

我希望我的应用程序能够在单击按钮时呼叫某个号码。我试过用谷歌搜索它,但到目前为止似乎没有一个适用于 iOS 10 的(openURL 不见了)。有人可以为我举个例子吗?例如像:

@IBAction func callPoliceButton(_ sender: UIButton) {
    // Call the local Police department
}

回答by Parth Adroja

You can call like this:

你可以这样调用:

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

For Swift 3+, you can use like

对于Swift 3+,您可以使用 like

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

OR

或者

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

Make sure you've scrubbed your phone number string to remove any instances of (, ), -, or space.

请确保您已擦洗你的手机串号删除的任何实例()-,或space

回答by Vasily Bodnarchuk

Task

任务

Make a call with phone number validation

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

Details

细节

Tested on:

测试:

  • Swift 5.2, Xcode 11.4 (11E146)
  • Swift 5.2,Xcode 11.4 (11E146)

Solution

解决方案

// MARK: DataDetector

class DataDetector {

    private class func _find(all type: NSTextCheckingResult.CheckingType,
                             in string: String, iterationClosure: (String) -> Bool) {
        guard let detector = try? NSDataDetector(types: type.rawValue) else { return }
        let range = NSRange(string.startIndex ..< string.endIndex, in: string)
        let matches = detector.matches(in: string, options: [], range: range)
        loop: for match in matches {
            for i in 0 ..< match.numberOfRanges {
                let nsrange = match.range(at: i)
                let startIndex = string.index(string.startIndex, offsetBy: nsrange.lowerBound)
                let endIndex = string.index(string.startIndex, offsetBy: nsrange.upperBound)
                let range = startIndex..<endIndex
                guard iterationClosure(String(string[range])) else { break loop }
            }
        }
    }

    class func find(all type: NSTextCheckingResult.CheckingType, in string: String) -> [String] {
        var results = [String]()
        _find(all: type, in: string) {
            results.append(
PhoneNumber(extractFrom: "+1-(800)-123-4567")?.makeACall()

PhoneNumber.extractAll(from: "+1-(800)-123-4567 bla bla 1(617)111-22-33").last?.makeACall()

PhoneNumber.first(in: "+1-(800)-123-4567 bla bla 1(617)111-22-33")?.makeACall()

"+1-(800)-123-4567 bla bla 1(617)111-22-33".detectedPhoneNumbers[1].makeACall()
"+1-(800)-123-4567 bla bla 1(617)111-22-33".detectedFirstPhoneNumber?.makeACall()
) return true } return results } class func first(type: NSTextCheckingResult.CheckingType, in string: String) -> String? { var result: String? _find(all: type, in: string) { result =
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("1(617)111-22-33!")
    isPhone("+44 1838 300284")
    isPhone("+44 1838 300284, 1 416 555 9292")
    isPhone("+44 1838 3d0384, 1 416 555 9292!")
}

private func isPhone(_ string: String) {
    let phoneNumbers = PhoneNumber.extractAll(from: string)
    let result = !phoneNumbers.isEmpty
    print("\(result ? "?" : "?") \(string) | detected phones: \(phoneNumbers)")
}
return false } return result } } // MARK: PhoneNumber struct PhoneNumber { private(set) var number: String init?(extractFrom string: String) { guard let phoneNumber = PhoneNumber.first(in: string) else { return nil } self = phoneNumber } private init (string: String) { self.number = string } func makeACall() { guard 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) } } static func extractAll(from string: String) -> [PhoneNumber] { DataDetector.find(all: .phoneNumber, in: string) .compactMap { PhoneNumber(string:
? blabla | detected phones: []
? +1(222)333-44-55 | detected phones: [+1(222)333-44-55]
? +42 555.123.4567 | detected phones: [555.123.4567]
? +1-(800)-123-4567 | detected phones: [+1-(800)-123-4567]
? +7 555 1234567 | detected phones: [+7 555 1234567]
? +7(926)1234567 | detected phones: [+7(926)1234567]
? (926) 1234567 | detected phones: [(926) 1234567]
? +79261234567 | detected phones: [+79261234567]
? 926 1234567 | detected phones: [926 1234567]
? 9261234567 | detected phones: [9261234567]
? 1234567 | detected phones: [1234567]
? 123-4567 | detected phones: [123-4567]
? 123-89-01 | detected phones: [123-89-01]
? 495 1234567 | detected phones: [495 1234567]
? 469 123 45 67 | detected phones: [469 123 45 67]
? 8 (926) 1234567 | detected phones: [8 (926) 1234567]
? 89261234567 | detected phones: [89261234567]
? 926.123.4567 | detected phones: [926.123.4567]
? 415-555-1234 | detected phones: [415-555-1234]
? 650-555-2345 | detected phones: [650-555-2345]
? (416)555-3456 | detected phones: [(416)555-3456]
? 202 555 4567 | detected phones: [202 555 4567]
? 4035555678 | detected phones: [4035555678]
?  1 416 555 9292 | detected phones: [1 416 555 9292]
? 1(617)111-22-33! | detected phones: [1(617)111-22-33]
? +44 1838 300284 | detected phones: [+44 1838 300284]
? +44 1838 300284, 1 416 555 9292 | detected phones: [+44 1838 300284, 1 416 555 9292]
? +44 1838 3d0384, 1 416 555 9292! | detected phones: [1 416 555 9292]
) } } static func first(in string: String) -> PhoneNumber? { guard let phoneNumberString = DataDetector.first(type: .phoneNumber, in: string) else { return nil } return PhoneNumber(string: phoneNumberString) } } extension PhoneNumber: CustomStringConvertible { var description: String { number } } // MARK: String extension extension String { // MARK: Get remove all characters exept numbers func onlyDigits() -> String { let filtredUnicodeScalars = unicodeScalars.filter { CharacterSet.decimalDigits.contains(
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 
   }
}
) } return String(String.UnicodeScalarView(filtredUnicodeScalars)) } var detectedPhoneNumbers: [PhoneNumber] { PhoneNumber.extractAll(from: self) } var detectedFirstPhoneNumber: PhoneNumber? { PhoneNumber.first(in: self) } }

Usage

用法

dialNumber(number: "+921111111222")

Full sample

完整样品

do not forget to paste the solution code here

不要忘记在此处粘贴解决方案代码

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

Result

结果

self.makeAPhoneCall()

回答by AbdulRehman Warraich

In Swift 4.2

在 Swift 4.2 中

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

Call this like below

像下面这样调用

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

Hope this help.

希望这有帮助。

回答by Kiran jadhav

Updated for Swift 3:

为 Swift 3 更新:

used below simple lines of code, if you want to make a phone call:

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

// function defination:

// 函数定义:

##代码##

// function call: [Used anywhere in your code]

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

##代码##

Note: Please run the app on a real device because it won't work on the simulator.

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

?

?

回答by Pratik Patel

##代码##

回答by Anjali jariwala

By mistake my answer was misplaced, please checkout this one: You can use this:

错误地我的答案放错了地方,请检查这个:你可以使用这个:

##代码##

We need to check whether we're on iOS 10 or later As 'openURL' was deprecated in iOS 10.0

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