iOS 10请求通知权限会触发两次

时间:2016-10-04 12:51:51

标签: ios objective-c permissions push-notification ios10

当我在 iOS 10 上启动我的应用时,我收到了两次请求通知权限。 第一个短暂出现并立即消失而不允许我做任何动作,然后我得到第二个弹出窗口,其中有正常行为等待“允许”“拒绝”用户。

这是我的代码在 iOS 10 之前运行良好。

来自 AppDelegate 的方法 didFinishLaunchingWithOptions

if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
#ifdef __IPHONE_8_0

    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
                                                                                         |UIRemoteNotificationTypeSound
                                                                                         |UIRemoteNotificationTypeAlert) categories:nil];
    [application registerUserNotificationSettings:settings];
#endif
} else {
    UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
    [application registerForRemoteNotificationTypes:myTypes];
}

我是否应该为iOS 10实现某些功能以修复此双重请求权限?

1 个答案:

答案 0 :(得分:-4)

对于iOS 10,我们需要在appDelegate didFinishLaunchingWithOptions方法中调用UNUserNotificationCenter。

首先,我们必须导入UserNotifications框架并在Appdelegate中添加UNUserNotificationCenterDelegate

AppDelegate.h

#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   if([[[UIDevice currentDevice]systemVersion]floatValue]<10.0)
   {
      [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound |    UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
      [[UIApplication sharedApplication] registerForRemoteNotifications];
   }
   else
   {
      UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
      center.delegate = self;
      [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error)
      {
         if( !error )
         {
             [[UIApplication sharedApplication] registerForRemoteNotifications];
             NSLog( @"Push registration success." );
         }
         else
         {
             NSLog( @"Push registration FAILED" );
             NSLog( @"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription );
             NSLog( @"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion );  
         }  
     }];  
   }
  return YES;
}

For more details