IOS – 如何在注销时禁用推送通知?

我的应用程序注册login在我的服务器的帐户,以启用推送通知聊天,但我还没有实现登出注销帐户,所以在这一刻,如果我做了2个帐户在同一设备的login采取这两个帐户的通知。 同时,我的通知中心有一个POST服务,从接收通知中心取消注册login_name +设备令牌。 我应该在哪里打电话? 我有使用unregisterForRemoteNotifications? 我只是想从推送通知注销accout +设备令牌,而不是永远禁用整个应用程序通知。

我可以将设备标记保存在didRegisterForRemoteNotificationsWithDeviceToken函数中

$ [[NSUserDefaults standardUserDefaults] setObject:hexToken forKey:DEVICE_KEY]; 

然后,在注销时,像我一样调用我的POST函数“removeDeviceToken”

  NSString *deviceToken = [userDefaults objectForKey:DEVICE_KEY]; if(deviceToken != NULL){ [self.engine removeDeviceToken:deviceToken]; } 

我不确定是否正确,但如果您不想禁用应用程序的推送通知,那么您不应该调用unregisterForRemoteNotifications。 你可以做的是,当用户点击注销button时,你可以向你的服务器发出注销请求,然后从该帐户中删除notificationID,注销请求完成后,你只需在本地执行注销(更新UI等等)。

有关评论的更多信息:

是的,首先,您应该在每次启动时调用registerForRemoteNotificationTypes方法,因为设备令牌可以更改。 在委托方法之后

 - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken 

被调用,你可以得到设备令牌并保存到NSUserDefault。 这样当用户login时,您可以获取最新的设备令牌(如果已更改),并将其发送到您的服务器以添加到该帐户。

所以代码可能看起来像这样

 - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken { NSString *newToken = [devToken description]; newToken = [newToken stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]; newToken = [newToken stringByReplacingOccurrencesOfString:@" " withString:@""]; NSString *notificationID = [newToken description]; NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; [prefs setObject:notificationID forKey:@"notification_id"]; [prefs synchronize]; } 

所以,现在当用户login时,只需获取通知ID并将其发送到您的服务器

 - (IBAction)userTappedLoginButton { // Make your login request // You can add the notification id as a parameter // depending on your web service, or maybe make // another request just to update notificationID // for a member NSString *notificationID = [[NSUserDefaults standardUserDefaults] objectForKey:@"notification_id"]; ... ... } 

您可以通过调用轻松启用和禁用应用程序中的推送通知

用于注册调用registerForRemoteNotificationTypes

 [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)]; 

用于取消注册调用unregisterForRemoteNotificationTypes

 [[UIApplication sharedApplication] unregisterForRemoteNotifications]; 

为检查使用

启用或禁用Iphone推送通知尝试此代码

 UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes]; if (types == UIRemoteNotificationTypeNone) // Yes it is..