我希望我的应用程序在后台或非活动模式下输入几秒后安排本地通知。这是我在视图控制器中完成的操作,当应用程序从中进入后台模式时:
class HomeViewController: UITableViewController {
override func viewDidLoad() {
...
let notificationCenter:NSNotificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: #selector(self.appMovedToBackground), name: UIApplicationWillResignActiveNotification, object: nil)
}
func appMovedToBackground() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
for userInfo in appDelegate.userInfoNotificationPending {
let localNotification = UILocalNotification()
localNotification.userInfo = userInfo
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.alertBody = userInfo["aps"]!["alert"] as? String
localNotification.fireDate = nil
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 2 * Int64(NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
UIApplication.sharedApplication().applicationIconBadgeNumber += 1
}
}
}
}
为什么它不起作用?
只要应用程序进入后台,就会立即调用app delegate中的didReceiveLocalNotification
方法。我在哪里弄错了?