2016-10-04 53 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