Reputation: 67
Hello I am currently doing a project where the user types something in a textfield, and presses a button, where whatever the user types in the textfield appears as part of the alertbody of a notification. To do this I save the textfield.text as a variable and then use string interpolation to include it into the alertbody. The problem is that the time in which I fire the notifications change every week, so I have to make new notifications. And I still want to use whatever the user typed into the textfield. But since the textfield.text was saved inside a function, I do not think that it will be stored outside the function. This is what my code looks like so far
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(604800, target: self,selector:Selector("repeater"), userInfo: nil, repeats: true)
}
savedtext:String!
@IBAction func setNotification{
textfield.text = savedtext
//set notifications and other stuff here
}
//outside the function savedtext should not have the textfield's info
func repeater{
//setting notification
}
Sorry if my question is a bit difficult to understand Any help is appreciated
Upvotes: 0
Views: 61
Reputation: 2032
I'd use NSUserDefaults
here, it will persist your data in a key-value map, even after the user or system kills the app. The code would look like this
let ALERT_MESSAGE_KEY : String = "myAlertMsgKey"
@IBAction func setNotification{
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(textfield.text , forKey: ALERT_MESSAGE_KEY)
NSUserDefaults.standardUserDefaults().synchronize()
//set notifications and other stuff here
}
and in repeater function:
func repeater {
let defaults = NSUserDefaults.standardUserDefaults()
let alertMessage = defaults.valueForKey(ALERT_MESSAGE_KEY) as? String ?? "No message saved"
}
You could also use Core Data for this, but it would be an overkill for something so simple
Upvotes: 3