我遇到的问题是,在iOS 10上重新安装应用程序后第一次调用registerForRemoteNotifications时,才调用didRegisterForRemoteNotificationsWithDevice。
发生了什么:在卸载应用程序然后在XCode的调试中运行应用程序后,我点击"允许"在应用内弹出窗口中,我确实收到了我的日志消息"用设备令牌注册了远程通知!",我得到了一个设备令牌。这让我犹豫地认为我的证书/配置文件没问题。但是,此设备令牌似乎不适用于发送推送通知(可能是服务器上的单独问题),关闭应用程序并重新打开后,我只看到"推送授权授予:1&# 34;和"推送注册开始。"但没有弹出窗口允许推送通知,也没有didRegister回调/令牌。
我尝试过寻找解决方案,但是我找不到第一次只显示didRegister功能的人,所以我不确定是什么原因造成的。
这是应用正在使用的代码:
-(void)registerForNotifications
{
#if !TARGET_IPHONE_SIMULATOR
if(SYSTEM_VERSION_LESS_THAN(@"10.0")) {
// This part is irrelevant, doesn't get called on iOS 10
-> some code for push notifications
}
else {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error)
{
NSLog(@"push authorization granted: %d", granted);
if(!error)
{
[[UIApplication sharedApplication] registerForRemoteNotifications];
NSLog(@"Push registration starting.");
}
else
{
NSLog(@"Push registration FAILED");
NSLog(@"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription);
NSLog(@"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion);
}
}];
}
#endif
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDevice :(NSData *)deviceToken
{
NSLog(@"did register for remote notifications with device!");
[self handleNewDeviceToken:deviceToken];
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken
{
NSLog(@"did register for remote notifications with device token!");
[self handleNewDeviceToken:deviceToken];
}
我希望这只是我身边的蠢事/配置文件或证书,我对iOS开发还不太熟悉。如果您可以使用任何其他信息,请告诉我。
修改 好吧,潜在的问题是我的代码每次调用register之前都调用unregisterForRemoteNotifications。显然,iOS10有一个更改,调用取消注册导致注册后不能工作一段时间。
答案 0 :(得分:1)
这看起来是一个iOS 10错误,而且有更多开发人员抱怨在这里遇到类似的问题:https://forums.developer.apple.com/thread/63038。
从我看到的情况来看,在您调用registerForRemoteNotifications
之后调用unregisterForRemoteNotifications
的后续尝试将不调用以下任何一个:
didRegisterForRemoteNotificationsWithDeviceToken
didFailToRegisterForRemoteNotificationsWithError
方法。基本上你没有收到来自iOS的任何回调。
我目前唯一知道的解决方法是向Info.plist添加后台提取功能。我可以确认这解决了我的问题,但你需要评估一下这个解决方案是否合理。
答案 1 :(得分:0)
对我来说,唯一有效的解决方案是并行使用旧式注册:
center.requestAuthorization(options: [.badge, .alert , .sound]) { (granted, error) in ... }
let notificationSettings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
application.registerUserNotificationSettings(notificationSettings)