如何在登录/注册后注册推送通知?

时间:2016-04-17 08:55:32

标签: ios swift parse-platform push-notification

我需要在登录/注册后将用户注册到Parse中的安装类,但它不会注册。没有打印错误,当我在appdeleag中断点时没有任何反应。

登录/注册后的viewcontroller的viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    UIApplication.sharedApplication().registerForRemoteNotifications()
}

的AppDelegate

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let installation = PFInstallation.currentInstallation()
    installation["user"] = PFUser.currentUser()
    installation.setDeviceTokenFromData(deviceToken)
    installation.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
        if (error == nil){
            print("saved installation")
        }else{
            print("error \(error)")
        }
    })
}

1 个答案:

答案 0 :(得分:0)

要注册以通过Apple Push服务接收推送通知,您必须使用registerForRemoteNotifications()方法调用UIApplication

如果注册成功,应用会调用您的应用委托对象的application:didRegisterForRemoteNotificationsWithDeviceToken:方法,并将其传递给设备令牌。

您应该将此令牌传递给您用于为设备生成推送通知的服务器。如果注册失败,应用会调用其应用代理的application:didFailToRegisterForRemoteNotificationsWithError:方法。

您可以参考此Appcoda's beginner guide for push notifiction

更新:

#pragma mark - push notificaiton
-(void)registerToReceivePushNotification {
// Register for push notifications
UIApplication* application =[UIApplication sharedApplication];
[application registerForRemoteNotificationTypes:
 UIRemoteNotificationTypeBadge |
 UIRemoteNotificationTypeAlert |
 UIRemoteNotificationTypeSound];
}

两个应用程序委托回调在app delegate

// handle user accepted push notification, update parse
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)newDeviceToken {
 // Store the deviceToken in the current installation and save it to Parse.
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
[currentInstallation setDeviceTokenFromData:newDeviceToken];

// enable future push to deviceId
NSUUID *identifierForVendor = [[UIDevice currentDevice] identifierForVendor];
NSString* deviceId = [identifierForVendor UUIDString];
[currentInstallation setObject:deviceId forKey:@"deviceId"];

[currentInstallation saveInBackground];
}


// handle push notification arrives when app is open
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
[PFPush handlePush:userInfo];
}

您可以随时进行注册通话 - 只有当您在应用中知道您希望用户接收推送通知时,才可以这样做。

两个应用程序委托回调必须在您的应用程序委托中,因为您在应用程序委托上注册通知类型而您只有一个。我建议使用一个应用委托方法来调用然后进行注册,你可以通过[[UIApplication sharedApplication]委托]从你的视图控制器调用它(将该调用的结果转换为你的应用程序委托类)。

代码在objective-c转换为swift。

希望这会有所帮助:)