检查iOS应用是否是从本地通知启动的?

时间:2015-08-17 06:42:33

标签: ios notifications

如何检测未处于活动,非活动或后台状态(已终止)的应用是否从本地通知启动?到目前为止,我已经在App Delegate的didFinishLaunchingWithOptions中尝试了两种方法:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // METHOD 1:
    if let options = launchOptions {
        if let key = options[UIApplicationLaunchOptionsLocalNotificationKey] {
            notificationCenter.postNotification(NSNotification(name: "applicationLaunchedFromNotification", object: nil))
        }
    }

    // METHOD 2:
    let notification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as! UILocalNotification!
    if (notification != nil) {
        notificationCenter.postNotification(NSNotification(name: "applicationLaunchedFromNotification", object: nil))
    }

    return true
}

在我的View Controller中,我观察ViewDidLoad中的通知,并在回复中设置UILabel的文本:

override func viewDidLoad() {
    super.viewDidLoad()
    notificationCenter.addObserver(self, selector: "handleAppLaunchFromNotification", name: "applicationLaunchedFromNotification", object: nil)
}

func handleAppLaunchFromNotification() {
    debugLabel.text = "app launched from notification"
}

但是,从本地通知启动已终止的应用程序后,UILabel的文本永远不会被设置。

我的问题是:

  1. 我做错了什么?
  2. 除了设置UILabel之外,还有更简单的方法来调试这样的情况吗?应用程序终止后,Xcode的调试器会分离应用程序,我无法使用print()

1 个答案:

答案 0 :(得分:0)

您正在检查didFinishLaunchingWithOptions此方法包含launchOptions的本地通知,仅用于远程通知。如果应用处于已终止状态,并且您对本地通知执行了操作,那么didReceiveLocalNotification方法会调用didFinishLaunchingWithOptions