2014-10-07 75 views
6

我试图按照解析指南来处理我JSON格式发送通知,但我有一个问题,这里是我的代码:Xcode中,解析 - 处理远程通知

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { 
     // Override point for customization after application launch. 
     Parse.setApplicationId("MyAppId", clientKey: "MyAppClientKey") 

     var notificationType: UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound 

     var settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationType, categories: nil) 
     UIApplication.sharedApplication().registerUserNotificationSettings(settings) 
     UIApplication.sharedApplication().registerForRemoteNotifications() 

if let launchOptions = launchOptions { 
    var notificationPayload: NSDictionary = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as NSDictionary! 
    println(launchOptions) 

    var url = notificationPayload["url"] as String 

    var feed: FeedTableViewController = FeedTableViewController() 
    feed.messages.insert(url, atIndex: 0) 
    feed.sections.insert("section", atIndex: 0) 
    } 


     return true 
    } 

的应用程序现在不会崩溃,但我所做的更改不会发生。 的Json代码:

{ 
    "aps": { 
     "badge": 10, 
     "alert": "Test", 
     "sound": "cat.caf" 
    }, 
    "url": "http://www.google.com" 
} 

回答

8

我猜你的问题是在这里:

launchOptions(UIApplicationLaunchOptionsRemoteNotificationKey) as NSDictionary 

我不知道你期待什么,但据我所知,有这样的方法没有在字典上。您可能正在寻找下标语法。事情是这样的:

launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as NSDictionary 

下得到的关键嵌套在launchOptions字典中的解释:UIApplicationLaunchOptionsRemoteNotificationKey。

也就是说,launchOptions可能为零,您应该在代码中添加该检查,并尝试记录launchOptions并在此处发布结果。

您可以检查是否launchOptions是零这样的:

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

请检查我的更新后,以及如果launchoptions ==更新了如何检查零零? – Abdou023 2014-10-07 20:27:54

+0

,我不知道该怎么如果他们为零,你应该怎么做,我假设他们是零,应用程序不是通过打开一个通知,你应该继续。 – Logan 2014-10-07 20:34:17

+0

这工作,但现在我不能让通知影响我的应用程序。请检查我的编辑。 – Abdou023 2014-10-07 21:09:31

3

的NSDictionary的objectForKey返回可选:

func objectForKey(_ aKey: AnyObject) -> AnyObject?

所以如果强制使用它的展开!如果Optional包含nil,则会带来风险。只有在100%确定Optional包含值时才应强制解包,但在此情况下,仅当用户在通知中心点击远程通知消息时启动应用程序时才设置UIApplicationLaunchOptionsRemoteNotificationKey。

您必须检查可选丧气的使用作为?:


if let myDict = launchOptions[UIApplicationLaunchOptionsRemoteNotifcationKey] as? NSDictionary { 
// there is a notification 
} else { 
// no notification 
} 

的NSDictionary到(以下简称“作为NSDictionary的?”没有严格要求,因为你可以在以后垂头丧气;如果你没有垂头丧气斯威夫特会警告你myDict对象将被推断为AnyObject。

+0

做到了这一点,仍然得到相同的错误。 – Abdou023 2014-10-07 20:58:58

2
if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary { 

}