2017-04-18 55 views
1

與swift3運行在xcode8如何從didReceiveRemoteNotification獲取數據返回數據?

下面是AppDelegate.swift

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { 
    print("==== didReceiveRemoteNotification ====") 
    print(userInfo) 
} 

我的代碼時,我得到的通知,並點擊它,我的調試區將如何像下面

==== didReceiveRemoteNotification ==== 
[AnyHashable("type"): order, AnyHashable("aps"): { 
    alert = "[TestMessage]"; 
    badge = "<null>"; 
    category = alert; 
    sound = default; 
}, AnyHashable("url"): http://www.google.com] 

我的問題是我如何使用userInfo從AnyHashable(「url」)獲取數據,即「www.google.com」?

我嘗試

print(userInfo[AnyHashable("url")]) 

但在調試區輸出

Optional(http://www.google.com) 
+0

請檢查更新的答案 –

回答

2
if let url = userInfo["url"] as? String { 
    //do whatever you need with the url 
} 
2

嘗試print(userInfo[AnyHashable("url")] as? String ?? "")或者你可以將它轉換爲URL

2
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { 
    if let aps = userInfo["aps"] as? NSDictionary { 
     print(aps) 
     let alert = (aps.object(forKey: "alert") as? String)! 
    } 

    let url = userInfo?["url"] as? String { 
     print(url) 
    } 
} 
相關問題