我有问题。我的项目中有本地通知,这里是代码(感谢@leoDabus):
import UIKit
class ViewController: UIViewController {
@IBOutlet var datePicker: UIDatePicker!
@IBOutlet var notificationSwitch: UISwitch!
let localNotification = UILocalNotification()
override func viewDidLoad() {
super.viewDidLoad()
setUpNotificationsOptions()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidAppear(animated: Bool) {
guard let loadedDate = NSUserDefaults().dateForKey("datePicker") else { return }
datePicker.setDate(loadedDate, animated: false)
}
func setUpNotificationsOptions() {
datePicker.datePickerMode = .Time
localNotification.timeZone = NSTimeZone.localTimeZone()
localNotification.repeatInterval = .Day
localNotification.alertAction = "Open App"
localNotification.alertBody = news[0].titleNews
localNotification.soundName = UILocalNotificationDefaultSoundName
}
func toggleNotification() {
if notificationSwitch.on {
localNotification.fireDate = datePicker.date.fireDate
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
} else {
localNotification.fireDate = nil
UIApplication.sharedApplication().cancelLocalNotification(localNotification)
}
}
@IBAction func toggleSwitch(sender: UISwitch) {
toggleNotification()
}
@IBAction func dateChanged(sender: UIDatePicker) {
NSUserDefaults().setDate(sender.date, forKey: "datePicker")
toggleNotification()
} }
extension NSUserDefaults {
func setDate(date: NSDate, forKey:String) {
NSUserDefaults().setObject(date, forKey: forKey)
}
func dateForKey(string:String) -> NSDate? {
return NSUserDefaults().objectForKey(string) as? NSDate
}}
问题是我的本地通知警报Body news [0] .titleNews是解析器的结果,它是一个定期更改的值。但是使用上面的代码我每天都获得相同的字符串,而不是更新的字符串。有一种方法可以每天更新新闻吗?我可以通过编程方式取消上次预定通知并安排新通知吗?
答案 0 :(得分:0)
在null
userInfo
属性中设置唯一ID,当您获得更新状态/新闻时,遍历所有预定通知,使用您之前设置的ID获取通知,现在执行你的工作相应。
设置您的ID,如下所示
UILocalNotification
遍历预定通知的代码
localNotification.userInfo = ["notificationID" : "Your Id"]