How to make data I enter in a UITextField inside a UIAlertController persist through resets in Swift?

喜欢而已 提交于 2019-12-25 16:51:26

问题


I have been trying to integrate a Pinboard bookmarks view (by parsing an RSS Feed and displaying it in a TableView) in my browser app. To get the username and API Token for the feed I have a UIAlertController in the Settings view of my app. The details entered are preserved through the session but if I force quit the app from the multitasking view, The details are deleted. How can I make them stay?

This is the code I'm using for the 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:


This question has been answered by Portland Runner in the comments to the question. The solution that worked was to save the text using NSUserDefaults.

Thanks Portland Runner! :)



来源:https://stackoverflow.com/questions/29868105/how-to-make-data-i-enter-in-a-uitextfield-inside-a-uialertcontroller-persist-thr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!