AziCode AziCode - 4 months ago 8
Swift Question

How to retrieve the detailedText from a cell then use it in a function?

I'm trying to retrieve the detailedText contained in a UITableView Cell (which is a phone number "String") and then Use it in a function that will make a phone call.


  • Problem:

    My app keeps crashing with the error "fatal error: unexpectedly found nil while unwrapping an Optional value "
    even though there is a value inside the variable.



I'm sure that I'm doing something wrong with force unwrapping the optional

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
let getPhone = cell?.detailTextLabel?.text

if indexPath.section == 0 && indexPath.row == 0 {

if let phoneNumber = getPhone{
openPhoneApp(phoneNumber)
}
}

// Open Phone App
func openPhoneApp(phoneNum: String){
UIApplication.sharedApplication().openURL(NSURL(string: "tel:\(phoneNum)")!)
}


enter image description here

Answer

Don't use force unwrapping if you're not 100% sure it can be unwrapped. And avoid it if possible even then!

Your openPhoneApp function must receive a non-nil string, so everything's ok up to that moment.

Try to replace your force unwrap with something like this:

func openPhoneApp(phoneNum: String) {
    guard let url = NSURL(string: "tel:\(phoneNum)") else {
        print("badly formed telephone url")
        return
    }
    UIApplication.sharedApplication().openURL(url)
}

Although I'd argue that your function's name implies that it WILL open the phone app, so maybe you should just go and ask for a correctly formed URL, like this:

func openPhoneApp(phoneURL: NSURL) {
    UIApplication.sharedApplication().openURL(phoneURL)
}

and check for that kind of stuff before even calling it:

if let phone = getPhone, phoneURL = NSURL(string: "tel:\(phone)") {
    openPhoneApp(phoneURL)
}