如何使我在UIAlertController中的UITextField中输入的数据通过Swift中的重置持续存在?

时间:2015-04-25 16:58:20

标签: ios swift uitextfield uialertcontroller

我一直在尝试在我的浏览器应用中集成Pinboard书签视图(通过解析RSS Feed并在TableView中显示它)。要获取Feed的用户名和API令牌,我在我的应用的“设置”视图中有一个UIAlertController。输入的详细信息将通过会话保留,但如果我强制退出多任务视图中的应用程序,则会删除详细信息。我怎么能让他们留下来?

这是我用于UIAlertController的代码:

@IBAction func pinboardUserDetailsRequestAlert(sender: AnyObject) {
    //Create the AlertController
    var pinboardUsernameField :UITextField?
    var pinboardAPITokenField :UITextField?
    let pinboardUserDetailsSheetController: UIAlertController = UIAlertController(title: "Pinboard Details", message: "Please enter your Pinboard Username and API Token to access your bookmarks", preferredStyle: .Alert)
    //Add a text field
    pinboardUserDetailsSheetController.addTextFieldWithConfigurationHandler({(usernameField: UITextField!) in
        usernameField.placeholder = "Username"
        var parent = self.presentingViewController as! ViewController
        usernameField.text = parent.pinboardUsername
        pinboardUsernameField = usernameField
    })
    pinboardUserDetailsSheetController.addTextFieldWithConfigurationHandler({(apiTokenField: UITextField!) in
        apiTokenField.placeholder = "API Token"
        var parent = self.presentingViewController as! ViewController
        apiTokenField.text = parent.pinboardAPIToken
        pinboardAPITokenField = apiTokenField
    })
    pinboardUserDetailsSheetController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
    pinboardUserDetailsSheetController.addAction(UIAlertAction(title: "Done", style: .Default, handler: { (action) -> Void in
        // Now do whatever you want with inputTextField (remember to unwrap the optional)
        var parent = self.presentingViewController as! ViewController
        parent.pinboardAPIToken = pinboardAPITokenField?.text
        parent.pinboardUsername = pinboardUsernameField?.text
    }))
    //Present the AlertController
    self.presentViewController(pinboardUserDetailsSheetController, animated: true, completion: nil)

}

1 个答案:

答案 0 :(得分:0)

Portland Runner在对该问题的评论中回答了这个问题。有效的解决方案是使用NSUserDefaults保存文本。

谢谢Portland Runner! :)