2017-03-17 100 views
0

我試圖在兩個單元(Subject「feedback」和「feedback2」)中實現MFMailComposeViewController()。MFMailComposeViewController not called

當我選擇每個單元格時,「反饋」運行良好,但「feedback2」未被調用。

這似乎並不困難的問題,但我覺得很難解決這個問題。

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 

     tableView.deselectRow(at: indexPath, animated: true) 

     if indexPath.row == 0 { 
      let message = "hey download this app" 
      let shareView = UIActivityViewController(activityItems: [message], applicationActivities: nil) 
      self.present(shareView, animated: true, completion: nil) 

     } else if indexPath.row == 1 { 
      let mailCompose = MFMailComposeViewController() 

      mailCompose.mailComposeDelegate = self 

      mailCompose.setToRecipients(["gmail.com"]) 

      mailCompose.setSubject("feedback") 

      mailCompose.setMessageBody("text", isHTML: false) 

      if MFMailComposeViewController.canSendMail() 

      { 

       self.present(mailCompose, animated: true, completion: nil) 

      } else if indexPath.row == 2 { 
       let mailCompose = MFMailComposeViewController() 

       mailCompose.mailComposeDelegate = self 

       mailCompose.setToRecipients(["[email protected]"]) 

       mailCompose.setSubject("feedback2") 

       mailCompose.setMessageBody("text", isHTML: false) 

       if MFMailComposeViewController.canSendMail() 

       { 

        self.present(mailCompose, animated: true, completion: nil) 

       } 

      else{ 

       print("error...!") 

      } 
     } 

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { 

     controller.dismiss(animated: true, completion: nil) 

    } 
+0

@ risa18任何錯誤,我想你在呼喚indexPath.row == 2在indexPath.row == 1裏面。 –

回答

2

else if indexPath.row == 2縮進一個級別太深 - 其else!MFMailComposeViewController.canSendMail(),不是以前indexPath檢查。您需要將該分支向外移動一個級別以獲得所需的效果。

對於未來,它可能是更容易,如果你重構了所有郵件,組成一個單一的方法來調試:

private func sendMail(to recipient: String, subject: String) { 
    if !MFMailComposeViewController.canSendMail() { 
     return 
    } 

    let mailCompose = MFMailComposeViewController() 
    mailCompose.mailComposeDelegate = self 
    mailCompose.setToRecipients([recipient]) 
    mailCompose.setSubject(subject) 
    mailCompose.setMessageBody("text", isHTML: false) 
    self.present(mailCompose, animated: true, completion: nil) 
} 

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    switch indexPath.row { 
     case 0: /* activity view controller stuff */ break; 
     case 1: 
      sendMail(to: "gmail.com", subject: "feedback") 
      break; 
     case 2: 
      sendMail(to: "[email protected]", subject: "feedback2") 
      break; 
    } 
} 
+1

爲了確保這種情況不會再發生,總是在與else/if語句相同的深度處放置一個括號也是非常有用的。 – Eric

+1

請在創建和設置作曲者之前檢查是否可以發送電子郵件。 – rmaddy

+0

@Tim很好的解決了這個問題! – risa8