使用UserDefault时,电子邮件主题显示为nil

时间:2017-06-02 21:50:35

标签: ios swift swift3

我有5个视图控制器,你在屏幕2上输入你的名字,它应该传递它的数据,以便在屏幕5,电子邮件屏幕,主题有你的名字。应该是:屏幕2:"比尔",屏幕5:"姓名:'比尔'",而是显示"姓名:nil&# 34 ;.我使用UserDefault传递数据, 这是我的屏幕2代码:

   @IBAction func extButton(_ sender: Any) {

    self.performSegue(withIdentifier: "whotoclass", sender: self)

}

func textFieldDidEndEditing(_ textField: UITextField) {

    UserDefaults.standard.setValue("your username", forKey: "UserName")
    UserDefaults.standard.synchronize()
    UserDefaults.standard.setValue(nil, forKey: "UserName")

}

屏幕5:

let strUserName = UserDefaults.standard.value(forKey: "UserName")


var myString = String()

@IBOutlet var pickerview2: UIPickerView!
@IBOutlet var label: UILabel!

let reason = ["Busy - General","Filming","Editing","Computer Task","Helping","Getting Set Up"]

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return reason[row]
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return reason.count
}

@IBAction func sendButton(_ sender: Any) {

    let toRecipients = ["thejoshytv@gmail.com"]

    let mc: MFMailComposeViewController = MFMailComposeViewController()

    mc.mailComposeDelegate = self

    mc.setToRecipients(toRecipients)
    mc.setSubject("Media Team Task")

    mc.setMessageBody("Hi There, A Notice to tell you that \(strUserName) will not be in class today.", isHTML: false)

    present(mc, animated: true, completion: nil)

}

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

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

    self.performSegue(withIdentifier: "reasontosent", sender: self)


}

1 个答案:

答案 0 :(得分:2)

我首先要删除完全不必要的

UserDefaults.standard.setValue(nil, forKey: "UserName")

您基本上将值设置为nil。

另一方面,UserDefauls定期保存到磁盘,因此在某些时候将其设置为nil将保留在磁盘上(之前的值将被删除)。

https://developer.apple.com/reference/foundation/userdefaults/1414005-synchronize

  

因为此方法会定期自动调用,   只有在您不能等待自动时才使用此方法   同步(例如,如果您的应用程序即将退出)或   如果要将用户默认值更新为磁盘上的内容,即使如此   你没有做任何改变。