2017-09-30 41 views
1

我的應用程序中有一個按鈕,用於觸發註冊通知。說這是一個UIBarButton註冊遠程通知不會產生任何效果

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Grant" style:UIBarButtonItemStyleDone target:self action:@selector(grantPermission:)]; 
self.navigationItem.rightBarButtonItem = rightButton; 

這是按鈕觸發功能:

- (void)grantPermission:(id)sender { 
    if (SYSTEM_VERSION_LESS_THAN(@"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) { 
      NSLog(@"Completion handler called"); 
      if (!error) { 
       dispatch_async(dispatch_get_main_queue(), ^{ 
        [[UIApplication sharedApplication] registerForRemoteNotifications]; 
       }); 
      } else { 
       NSLog(@"Push registration FAILED"); 
       NSLog(@"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription); 
       NSLog(@"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion); 
      } 
     }]; 
    } 
} 

我還增加了以下的委託方法:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
    NSLog(@"Did Register for Remote Notifications with Device Token (%@)", deviceToken); 
} 

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { 
    NSLog(@"Did Fail to Register for Remote Notifications"); 
    NSLog(@"%@, %@", error, error.localizedDescription); 
} 

當我運行這段代碼,我得到的模態請求許可。當我按'接受'時,我看到Completion handler called日誌,但沒有任何記錄。沒有任何反應,沒有顯示日誌。沒有。任何想法,我做錯了什麼?

+0

[爲什麼didRegisterForRemoteNotificationsWithDeviceToken不叫(https://stackoverflow.com/questions/4086599/why-didregisterforremotenotificationswithdevicetoken-is-not-called) – Honey

+0

圍棋的可能的複製,另外你使用的是設備還是模擬器?因爲你將無法通過模擬器獲得令牌! – Honey

回答

0

您必須在物理設備上測試該代碼。模擬器不會收到通知令牌。你會得到一個錯誤回調。

此外,請檢查您的iOS版本,因爲應用程序委託中的回調在ios9-10(可能爲11)之間發生變化,因此您將有一個不會被調用的反用方法(或反之亦然,具體取決於哪個iOS系統的版本,你是通過所有的答案測試反對)