Android 取消注册推送通知令牌

Android 取消注册推送通知令牌,android,ios,xamarin,xamarin.ios,xamarin.android,Android,Ios,Xamarin,Xamarin.ios,Xamarin.android,我刚刚从一个竞争对手手中接过一个代码,它已经在GCM上启动了。 但是,由于我将为其创建应用程序的公司在其数据基础上做出了一些错误的决定(只允许每个用户在令牌上存储),应用程序用户必须注销其令牌,以便该公司能够正确存储令牌 在安卓上,我在想,这是否足够 var instanceId = InstanceID.GetInstance(Android.App.Application.Context); instanceId?.DeleteInstanceID(); 我完全不知道如何在iOS上实现这一

我刚刚从一个竞争对手手中接过一个代码,它已经在GCM上启动了。 但是,由于我将为其创建应用程序的公司在其数据基础上做出了一些错误的决定(只允许每个用户在令牌上存储),应用程序用户必须注销其令牌,以便该公司能够正确存储令牌

在安卓上,我在想,这是否足够

var instanceId = InstanceID.GetInstance(Android.App.Application.Context);
instanceId?.DeleteInstanceID();
我完全不知道如何在iOS上实现这一点:(

iOS注册为

public static void RegisterForPushNotification()
{
   if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
   {
      var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, new NSSet());
      UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
      UIApplication.SharedApplication.RegisterForRemoteNotifications();
   }
   else
   {
      UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
      UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
   }
}

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
   var DeviceToken = deviceToken.Description;

   var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");

   NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");
}
第二手的Windows没有注册,所以我不必从那里注销,只需注册即可

国际监督组织目标C

AppDelegate.h

#import <UIKit/UIKit.h>
#import <Google/CloudMessaging.h>



@interface AppDelegate : UIResponder <UIApplicationDelegate,GGLInstanceIDDelegate, GCMReceiverDelegate>


@property (strong, nonatomic) UIWindow *window;

// [GCM register_for_remote_notifications]

@property(nonatomic, readonly, strong) NSString *registrationKey;
@property(nonatomic, readonly, strong) NSString *messageKey;
@property(nonatomic, readonly, strong) NSString *gcmSenderID;
@property(nonatomic, readonly, strong) NSDictionary *registrationOptions;
#导入
#进口
@接口AppDelegate:UIResponder
@属性(强,非原子)UIWindow*window;
//[GCM注册用于远程通知]
@属性(非原子、只读、强)NSString*registrationKey;
@属性(非原子、只读、强)NSString*messageKey;
@属性(非原子、只读、强)NSString*gcmSenderID;
@属性(非原子、只读、强)NSDictionary*注册选项;
//AppDelegate.m

#import "AppDelegate.h"


@interface AppDelegate ()

@property(nonatomic, strong) void (^registrationHandler)
(NSString *registrationToken, NSError *error);
@property(nonatomic, assign) BOOL connectedToGCM;
@property(nonatomic, strong) NSString* registrationToken;
@property(nonatomic, assign) BOOL subscribedToTopic;

@end


NSString *const SubscriptionTopic = @"/topics/global";


@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {


 #if !(TARGET_IPHONE_SIMULATOR)

    [self setUpGCMClientApp];

 #endif

    return YES;
}




-(void)setUpGCMClientApp{


    // [START_EXCLUDE]
    _registrationKey = @"onRegistrationCompleted";
    _messageKey = @"onMessageReceived";
    // Configure the Google context: parses the GoogleService-Info.plist, and initializes
    // the services that have entries in the file
    NSError* configureError;
    [[GGLContext sharedInstance] configureWithError:&configureError];
    if (configureError != nil) {
        NSLog(@"Error configuring the Google context: %@", configureError);
    }
    _gcmSenderID = [[[GGLContext sharedInstance] configuration] gcmSenderID];
    // [END_EXCLUDE]
    // Register for remote notifications
    UIUserNotificationType allNotificationTypes =
    (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings =
    [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    // [END register_for_remote_notifications]
    // [START start_gcm_service]
    [[GCMService sharedInstance] startWithConfig:[GCMConfig defaultConfig]];
    // [END start_gcm_service]
    __weak typeof(self) weakSelf = self;
    // Handler for registration token request
    _registrationHandler = ^(NSString *registrationToken, NSError *error){
        if (registrationToken != nil) {
            weakSelf.registrationToken = registrationToken;
            NSLog(@"Registration Token: %@", registrationToken);
            [weakSelf subscribeToTopic];
            [ApplicationPreference saveValue:registrationToken forKey:KGCM_RegistrationToken];
            NSDictionary *userInfo = @{@"registrationToken":registrationToken};
            [[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKey
                                                                object:nil
                                                              userInfo:userInfo];

            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startLocating:) name:@"ForceUpdateLocation" object:nil]; // don't forget the ":"

        } else {
            NSLog(@"Registration to GCM failed with error: %@", error.localizedDescription);
            NSDictionary *userInfo = @{@"error":error.localizedDescription};
            [[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKey
                                                                object:nil
                                                              userInfo:userInfo];
        }
    };

    [[NSNotificationCenter defaultCenter] postNotificationName:_messageKey
                                                        object:nil
                                                      userInfo:nil];





}



- (void)subscribeToTopic {
    // If the app has a registration token and is connected to GCM, proceed to subscribe to the
    // topic
    if (_registrationToken && _connectedToGCM) {
        [[GCMPubSub sharedInstance] subscribeWithToken:_registrationToken
                                                 topic:SubscriptionTopic
                                               options:nil
                                               handler:^(NSError *error) {
                                                   if (error) {
                                                       // Treat the "already subscribed" error more gently
                                                       if (error.code == 3001) {
                                                           NSLog(@"Already subscribed to %@",
                                                                 SubscriptionTopic);
                                                       } else {
                                                           NSLog(@"Subscription failed: %@",
                                                                 error.localizedDescription);
                                                       }
                                                   } else {
                                                       self.subscribedToTopic = true;
                                                       NSLog(@"Subscribed to %@", SubscriptionTopic);
                                                   }
                                               }];
    }
}



// [START disconnect_gcm_service]
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    [[GCMService sharedInstance] disconnect];
    // [START_EXCLUDE]
    _connectedToGCM = NO;
    // [END_EXCLUDE]
}
// [END disconnect_gcm_service]

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    // Connect to the GCM server to receive non-APNS notifications
    [[GCMService sharedInstance] connectWithHandler:^(NSError *error) {
        if (error) {
            NSLog(@"Could not connect to GCM: %@", error.localizedDescription);
        } else {
            _connectedToGCM = true;
            NSLog(@"Connected to GCM");
            // [START_EXCLUDE]
            [self subscribeToTopic];
            // [END_EXCLUDE]
        }
    }];
}
// [END connect_gcm_service]



// [START receive_apns_token]
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    NSString *device_Token = [[NSString alloc] init];

    device_Token = [[[[deviceToken description]
                      stringByReplacingOccurrencesOfString: @"<" withString: @""]
                     stringByReplacingOccurrencesOfString: @">" withString: @""]
                    stringByReplacingOccurrencesOfString: @" " withString: @""];

    NSLog(@"deviceToken = %@",device_Token);

    [[NSUserDefaults standardUserDefaults] setObject:device_Token forKey:kDEVICETOKEN];
    // [END receive_apns_token]
    // [START get_gcm_reg_token]
    // Start the GGLInstanceID shared instance with the default config and request a registration
    // token to enable reception of notifications
    [[GGLInstanceID sharedInstance] startWithConfig:[GGLInstanceIDConfig defaultConfig]];
    _registrationOptions = @{kGGLInstanceIDRegisterAPNSOption:deviceToken,
                             kGGLInstanceIDAPNSServerTypeSandboxOption:@YES};
    [[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID
                                                        scope:kGGLInstanceIDScopeGCM
                                                      options:_registrationOptions
                                                      handler:_registrationHandler];
    // [END get_gcm_reg_token]
}

// [START receive_apns_token_error]
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Registration for remote notification failed with error: %@", error.localizedDescription);
    // [END receive_apns_token_error]
    NSDictionary *userInfo = @{@"error" :error.localizedDescription};
    [[NSNotificationCenter defaultCenter] postNotificationName:_registrationKey
                                                        object:nil
                                                      userInfo:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"Notification received: %@", userInfo);
    // This works only if the app started the GCM service
    [[GCMService sharedInstance] appDidReceiveMessage:userInfo];
    // Handle the received message
    // [START_EXCLUDE]
    [[NSNotificationCenter defaultCenter] postNotificationName:_messageKey
                                                        object:nil
                                                      userInfo:userInfo];
    // [END_EXCLUDE]
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
    NSLog(@"Notification received: %@", userInfo);
    // This works only if the app started the GCM service
    [[GCMService sharedInstance] appDidReceiveMessage:userInfo];
    // Handle the received message
    // Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
    // [START_EXCLUDE]
    [[NSNotificationCenter defaultCenter] postNotificationName:_messageKey
                                                        object:nil
                                                      userInfo:userInfo];
    handler(UIBackgroundFetchResultNoData);
    // [END_EXCLUDE]
}
// [END ack_message_reception]

// [START on_token_refresh]
- (void)onTokenRefresh {
    // A rotation of the registration tokens is happening, so the app needs to request a new token.
    NSLog(@"The GCM registration token needs to be changed.");
    [[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID
                                                        scope:kGGLInstanceIDScopeGCM
                                                      options:_registrationOptions
                                                      handler:_registrationHandler];
}



// [END on_token_refresh]

// [START upstream_callbacks]
- (void)willSendDataMessageWithID:(NSString *)messageID error:(NSError *)error {
    if (error) {
        // Failed to send the message.
    } else {
        // Will send message, you can save the messageID to track the message
    }
}

- (void)didSendDataMessageWithID:(NSString *)messageID {
    // Did successfully send message identified by messageID
}
// [END upstream_callbacks]

- (void)didDeleteMessagesOnServer {
    // Some messages sent to this device were deleted on the GCM server before reception, likely
    // because the TTL expired. The client should notify the app server of this, so that the app
    // server can resend those messages.
}




@end
#导入“AppDelegate.h”
@接口AppDelegate()
@属性(非原子,强)void(^registrationHandler)
(NSString*注册令牌,NSError*错误);
@属性(非原子,赋值)BOOL connectedToGCM;
@属性(非原子,强)NSString*registrationToken;
@属性(非原子,赋值)BOOL subscribedtototopic;
@结束
NSString*const SubscriptionTopic=@“/主题/全局”;
@实现AppDelegate
-(BOOL)应用程序:(UIApplication*)应用程序使用选项完成启动:(NSDictionary*)启动选项{
#如果!(目标IPHONE模拟器)
[自设置GCMClientApp];
#恩迪夫
返回YES;
}
-(无效)设置GCMClientApp{
//[开始时不包括]
_registrationKey=@“onRegistrationCompleted”;
_messageKey=@“onMessageReceived”;
//配置Google上下文:解析GoogleService-Info.plist并初始化
//文件中包含条目的服务
n错误*配置错误;
[[GlgContext sharedInstance]配置错误:&configureError];
如果(配置错误!=nil){
NSLog(@“配置Google上下文时出错:%@”,配置错误);
}
_gcmSenderID=[[GGLContext sharedInstance]配置]gcmSenderID];
//[完]
//注册远程通知
UIUserNotificationType所有NotificationType=
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings*设置=
[UIUserNotificationSettings设置类型:allNotificationTypes类别:nil];
[[UIApplication sharedApplication]注册表通知设置:设置];
[[UIApplication sharedApplication]注册表项的删除];
//[用于远程通知的结束寄存器\u]
//[启动\u gcm\u服务]
[[GCMService sharedInstance]startWithConfig:[GCMConfig defaultConfig]];
//[结束-启动\u gcm\u服务]
__弱类型(自我)弱自我=自我;
//注册令牌请求的处理程序
_registrationHandler=^(NSString*registrationToken,NSError*error){
如果(注册令牌!=nil){
weakSelf.registrationToken=registrationToken;
NSLog(@“注册令牌:%@”,注册令牌);
[weakSelf subscribetopic];
[ApplicationPreference保存值:registrationToken forKey:KGCM_registrationToken];
NSDictionary*userInfo=@{@“registrationToken”:registrationToken};
[[NSNotificationCenter defaultCenter]postNotificationName:weakSelf.registrationKey
对象:无
userInfo:userInfo];
[[NSNotificationCenter defaultCenter]addObserver:自选择器:@selector(惊人的:)名称:@“ForceUpdateLocation”对象:nil];//别忘了“:”
}否则{
NSLog(@“注册到GCM失败,错误:%@”,错误。localizedDescription);
NSDictionary*userInfo=@{@“error”:error.localizedDescription};
[[NSNotificationCenter defaultCenter]postNotificationName:weakSelf.registrationKey
对象:无
userInfo:userInfo];
}
};
[[NSNotificationCenter defaultCenter]postNotificationName:\u messageKey
对象:无
用户信息:无];
}
-(无效)下标{
//如果应用程序具有注册令牌并连接到GCM,则继续订阅
//话题
if(_registrationToken&&u connectedToGCM){
[[GCMPubSub sharedInstance]SubscribowithToken:\u registrationToken
主题:订阅主题
选项:无
处理程序:^(n错误*错误){
如果(错误){
//更温和地对待“已订阅”错误
如果(错误代码==3001){
NSLog(@“已订阅%@”,
下标图);
}否则{
NSLog(@“订阅失败:%@”,
错误。本地化描述);
}
}否则{
self.subscribedToTopic=true;