How to register for GCM in iOS

天大地大妈咪最大 提交于 2019-12-10 17:43:02

问题


I can't seem to get GCM push notifications working. My problem is I don't know how to get a registration ID from GCM. I can get a token from APN just fine. But I'm not quite sure what to do next. I tried following the tutorial but its not really working for me. I'm a beginner so please be explicit.

What I'm asking is, after obtaining a token from APN, then what do I do?

Thanks in advance. https://developers.google.com/cloud-messaging/ios/client


回答1:


The Registration Token is given to the registration handler from didRegisterForRemoteNotificationsWithDeviceToken

All code below is taken from the GCM Sample from Google.

First, declare a handler in your application:didFinishLaunchingWithOptions:

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

Call your handler in the application registration callback:

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // 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];
}

The GCM token to use is simply the "NSString *registrationToken" in the registration handler.



来源:https://stackoverflow.com/questions/30820618/how-to-register-for-gcm-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!