我开发了一个应用程序,其中实现了推送通知。目前它在苹果商店上线。直到 iOS 9 推送工作正常,但在 iOS 10 之后它不工作。
代码有什么问题?
最佳答案
对于使用 xCode 8 GM 的 iOS 10。
我已经使用适用于 iOS 10 的 xCode 8 GM 通过以下步骤解决了我的问题:
1) 在目标中,在 Capabilities 下启用 Push Notifications 添加 Push Notifications Entitlements。
2) 在您的应用中实现 UserNotifications.framework。在您的 AppDelegate 中导入 UserNotifications.framework。
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
@end
3) 在 didFinishLaunchingWithOptions 方法中分配 UIUserNotificationSettings
并实现 UNUserNotificationCenter
委托(delegate)。
#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0")){
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
if( !error ){
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
}];
}
return YES;
}
4) 现在终于实现了这两个委托(delegate)方法。
//============iOS 10=============
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
//Called when a notification is delivered to a foreground app.
NSLog(@"Userinfo %@",notification.request.content.userInfo);
completionHandler(UNNotificationPresentationOptionAlert);
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
//Called to let your app know which action was selected by the user for a given notification.
NSLog(@"Userinfo %@",response.notification.request.content.userInfo);
}
请保留您在 iOS 9 中使用的代码, 仅添加代码行以使用 UserNotifications.framework 支持 iOS 10 的推送通知。
关于ios - iOS 10 的推送通知问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39490605/