如何在iOS中注册GCM

3
我似乎无法让GCM推送通知正常工作。我的问题是我不知道如何从GCM获取注册ID。我可以轻松地从APN获取令牌,但我不太确定接下来该怎么做。我尝试按照教程操作,但对我来说并没有真正起作用。作为初学者,请详细说明一下。
我的问题是,在从APN获取令牌之后,我该怎么做?
提前致谢。 https://developers.google.com/cloud-messaging/ios/client
1个回答

4

注册令牌是从didRegisterForRemoteNotificationsWithDeviceToken方法中传递给注册处理程序的。

以下所有代码均来自Google的GCM示例。

首先,在应用程序的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];
    }
};

在应用程序注册回调函数中调用您的处理程序:

- (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];
}

使用的 GCM 令牌只是注册处理程序中的 "NSString *registrationToken"。

注册令牌(registrationToken)是用于在服务器端识别通知接收者的吗?还是只是在设备端使用GCM API时使用的授权令牌?这在GCM iOS文档中并没有明确说明。 - Tapani
@Tapani,是的,在那里收到的registrationToken是用于在从服务器发送推送时识别接收者的标识符。 - Jeremy
不确定您是否能提供帮助,但当我从存档中运行我的应用程序时,_registrationHandler = 代码不会运行,我也无法获得令牌。如果我直接从Xcode运行到我的设备上,它就可以正常工作。这里有什么想法吗? - Rob85
在 didFinishLaunching 的 _registrationHandler 回调中,我得到了 registrationToken 为 nil 的情况。有什么想法吗? 我已经验证了传递给 _registrationOptions 字典的 deviceToken 不为空。 - JiteshW
@JeremyLee,错误对象返回的代码为0。根据Google GCM文档,它是“无效请求-请求的某些参数无效”。我不知道原因。我有发送者ID,字典不为空(deviceToken是去除空格和<>后的字符串),范围为kGGLInstanceIDScopeGCM。已添加GoogleService-Info.plist文件。 - JiteshW
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接