Reputation: 2692
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)")!)
}
Upvotes: 0
Views: 61
Reputation: 2685
Please use tel:// scheme and always call
UIApplication.sharedApplication().canOpenURL
before
Upvotes: 1
Reputation: 4593
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)
}
Upvotes: 3
Reputation: 414
Did you checked the value of phoneNumber variable? it could be nil.
You can check this answer: I think this will solve your problem.
What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?
specifically this answer
https://stackoverflow.com/a/35683816/5660422
Upvotes: 1