簡體   English   中英

如何使用swift從launchOptions獲取自定義推送通知值?

[英]How to get custom Push Notification value from launchOptions with swift?

我正在使用Swift構建一個接收推送通知的應用程序。 我在JSON中發送自定義值。

我通過通知打開應用程序,所以我知道我必須在“didFinishLaunchingWithOptions”中執行此操作並從“launchOptions”中讀取值。

如何閱讀這些值並在我的應用程序中使用它們。

非常感謝。

當您的應用未啟動時,這是適用於SWIFT 2的功能。 由於可選的綁定,代碼不是很優雅。 但它的確有效。

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

    // if launched from a tap on a notification
    if let launchOptions = launchOptions {
        if let userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] {
            if let action = userInfo["action"], id = userInfo["id"] {
                let rootViewController = self.window!.rootViewController as! ViewController
                let _ = setTimeout(5.0, block: { () -> Void in
                    rootViewController.openNotification(action as! String, id: id as! String)
                })

            }
        }
    }
    return true
}

在應用程序中:didReceiveRemoteNotification:fetchCompletionHandler,自定義數據傳遞給didReceiveRemoteNotification,這是一個NSDictionary。 您要檢索的詳細信息可能位於userInfo的“aps”鍵上。

func application(application: UIApplication, didReceiveRemoteNotification userInfo: NSDictionary!)
{
    var notificationDetails: NSDictionary = userInfo.objectForKey("aps") as NSDictionary
}

當應用程序未啟動時,您需要從應用程序中獲取它:didFinishedLaunchWithOptions,

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {

    if let launchOpts = launchOptions {
      var notificationDetails: NSDictionary = launchOpts.objectForKey(UIApplicationLaunchOptionsRemoteNotificationKey) as NSDictionary
    }

    return true
}

編輯:遠程通知修復語法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM