应用关闭时点击UILocalNotifications

时间:2015-08-12 14:36:23

标签: ios swift uilocalnotification

我正在做这个需要在事件发生时发送通知的应用。

一切正常,但是当应用程序关闭并且通过通知打开时,它不会触发它应该如何。

我的应用代表didFinishLaunchingWithOptions和didReceiveLocalNotification

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    createCopyOfDatabaseIfNeeded()

    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound |
        UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))

    if let options = launchOptions {
        let value = options[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification
        if let notification = value {
            self.application(application, didReceiveLocalNotification: notification)
        }
    }
    return true
}

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    // Do something serious in a real app.
    println("Received Local Notification:")
    println(notification.alertBody)


    if notification.alertAction == "editList" {
        NSNotificationCenter.defaultCenter().postNotificationName("modifyListNotification", object: nil);
    }


}

在我的主标签控制器中:

override func viewDidLoad() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleModifyListNotification", name: "modifyListNotification", object: nil)
    super.viewDidLoad()
    self.repaint()
}


func handleModifyListNotification(){
    dispatch_async(dispatch_get_main_queue(), {
        // Show the alert
    })

}

主要目标是在应用程序关闭时按下通知,打开,执行didFinishLaunchingWithOptions并检查launchOptions中的UILocalNotification并调用didReceiveLocalNotification。

ps:我知道调试时通知很好,系统就是不应该调用didReceiveLocalNotification方法。

1º编辑

我真的在调用didReceiveLocalNotifaction方法,因为我只是尝试了这个并且它有效

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    // Do something serious in a real app.
    println("Received Local Notification:")
    println(notification.alertBody)



    if notification.alertAction == "editList" {

        var xpto = UIAlertView()
        xpto.title = notification.alertAction!
        xpto.show() NSNotificationCenter.defaultCenter().postNotificationName("modifyListNotification", object: nil);
    }


}

所以我认为这必须是一个时间问题。我真的希望我的标签控制器对此通知做出反应。

NSNotificationCenter.defaultCenter().postNotificationName("modifyListNotification", object: nil);

1 个答案:

答案 0 :(得分:3)

如果我没弄错的话,-didReceiveLocalNotification:仅在应用处于活动状态并被使用时被调用。

如果您尝试从后台状态启动应用,我建议使用-didFinishLaunchingWithOptions:并查询您的选项。

出于这个原因,可能在单独的方法中使用您的通知处理代码,并从-didReceiveLocalNotification& -didFinishLaunchingWithOptions?