Search code examples
swiftnullruntime-erroroptional-values

MailComposeViewController Error: unexpectedly found nil


I'm trying to save the email and time of an email i sent, to a table view. The emails send fine, but I get this error (Error: unexpectedly found nil while unwrapping an Optional value) whenever I click the send button. I'm not sure where is the error in my code.

The code for the send button:

//SentEmails Array
var sentEmails = [emailObject]()

//Default email
var sentEmailTo = "[email protected]"

//Dismiss Buttons for Mail Composer
func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError?) {

    //Check for errors
   if let error = error {
        print("Error: \(error)")
        return
    }

    switch result {
    case MFMailComposeResultCancelled:
        print("Mail Cancelled")
    case MFMailComposeResultSaved:
        print("Mail Saved")
    case MFMailComposeResultSent:

     //Save information to tableview
        let emailSent = emailObject(sentTo: sentEmailTo, timeSent: NSDate())
        sentEmails.append(emailSent)
        tableView.reloadData()

        print("Mail Sent")

    case MFMailComposeResultFailed:
        print("Mail sent failure: \(error)")
    default:
        break
    }

    controller.dismissViewControllerAnimated(true, completion: nil)
}

My cell code:

//Cell Configuration
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)

    let row = indexPath.row

    let dateFormat = NSDateFormatter()
    dateFormat.dateStyle = .ShortStyle
    dateFormat.timeStyle = .ShortStyle
    cell.textLabel?.text = sentEmails[row].sentTo
    cell.detailTextLabel?.text = dateFormat.stringFromDate(sentEmails[row].timeSent)



    return cell
}

The error:

enter image description here

*Didn't know I could do this lol, here's the error detail:

enter image description here


Solution

  • Do you have the tableView connected in interface builder like this? You need to define your datasource, delegate and outlets for the table if not (the "Gratitude Stream" bits are from my example but yours will be from your own view controller). enter image description here