解析 - 设置设备令牌

时间:2014-11-13 03:48:13

标签: ios xcode swift parse-platform

我正在尝试在解析中设置设备令牌。官方文档提供了以下代码来执行此操作

官方文档(目标C)

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  // Store the deviceToken in the current installation and save it to Parse.
  PFInstallation *currentInstallation = [PFInstallation currentInstallation];
  [currentInstallation setDeviceTokenFromData:deviceToken];
  currentInstallation.channels = @[ @"global" ];
  [currentInstallation saveInBackground];
}

我已将代码转换为如下所示,但收到错误。

我的代码(Swift)

func application( applcation: UIApplication!, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData! ) {
    println(deviceToken)

  let currentInstallation = PFInstallation.currentInstallation()

            currentInstallation .setDeviceTokenFromData(deviceToken)
            currentInstallation .setObject(PFUser.currentUser(), forKey: "owner")
            currentInstallation .addUniqueObject("Test", forKey: "channels")
            currentInstallation .save()

运行我的代码时收到以下错误:

 Break on warnBlockingOperationOnMainThread() to debug.
2014-11-13 03:44:01.306 Meetr[8855:2084537] Error: invalid type for key deviceToken, expected array, but got string (Code: 111, Version: 1.4.2)
sent

有人可以帮我解释为什么会这样吗?我很困惑,因为我只是简单地将原始目标C代码转换为swift。

提前致谢。

4 个答案:

答案 0 :(得分:3)

我只是设置我的Parse通知而没有任何问题。你遇到错误的地方就是我的错误,所以我不认为问题是什么。这是我在App Delegate中所拥有的一切:

    func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    // Override point for customization after application launch.

    //ENABLE PUSH NOTIFICATIONS
    let userNotificationTypes = (UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound)
    let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
    application.registerUserNotificationSettings(settings)
    application.registerForRemoteNotifications()

    return true

}

func application(application: UIApplication!, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData!) {
    //Store the deviceToken in the current installation and save it to Parse.

    let currentInstallation: PFInstallation = PFInstallation.currentInstallation()
    currentInstallation.setDeviceTokenFromData(deviceToken)
    currentInstallation.saveInBackground()
}

func application(application: UIApplication!, didReceiveRemoteNotification userInfo: NSDictionary!) {
    PFPush.handlePush(userInfo)
}

答案 1 :(得分:0)

错误表明类型错误:

Error: invalid type for key deviceToken, expected array, but got string (Code: 111, Version: 1.4.2)

只需将数据从String(" deviceToken")更改为数组([" deviceToken"])。

答案 2 :(得分:0)

不确定问题是什么开始但是,删除类并在解析中重新创建似乎解决了它。很奇怪..

答案 3 :(得分:0)

将此代码用于swift 3.0

let installation = PFInstallation.current()
installation.setObject(Token, forKey: "deviceToken")

if(installation.badge != 0)
{
  installation.badge = 0
}
installation.saveEventually()