Search code examples
iosswiftphone-numberphone-call

iOS Swift call Crashes because of Invalid mobile number


This is the code I am using to make call. But it crashes because of invalid number. the number with 11 digits starts with 6 crashes but the number with 11 digits starts with 0 works fine normally with 10 digits works fine. Can anyone help?

let myurl=URL(string: "tel://\(selectedEmployeeContact)")
    let isInstalled=UIApplication.shared.canOpenURL(myurl!)
    if(isInstalled)
    {
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(myurl!)
        } else {
            UIApplication.shared.openURL(myurl!)
        }
    }

Solution

  • Modify your code to prevent the crash:-

    guard let myurl=URL(string: "tel://\(selectedEmployeeContact)") else {return}
    let isInstalled=UIApplication.shared.canOpenURL(myurl)
    

    If your myurl is nil then it will crash because it will force unwrapped the Value.