2016-10-04 62 views
1

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

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

在该方法中didFinishLaunchingWithOptions的AppDelegate

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

见这是在迅速:https://iosdevcenters.blogspot.com/2016/09/usernotifications-framework-push.html –

回答

-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

+2

对建议的代码要格外小心。在回调函数中,您假定'!error'意味着用户已经为通知授予了权限,而这不正确。如果用户拒绝接收通知,您将收到'granted = NO'和'error = nil',破坏您的逻辑。 – tomacco

+0

像这样检查API可用性是一种不好的做法。考虑使用'[UNUserNotificationCenter class]!= nil'和'respondsToSelector:'方法。 – vahotm