1. 程式人生 > >iOS開發 --- 推送 SDK: Main Thread Checker: UI API called on a background thread

iOS開發 --- 推送 SDK: Main Thread Checker: UI API called on a background thread

Xcode 升級到 Xcode 9後,整合時若提示下述錯誤:

  1. MainThreadChecker: UI API called on a background thread

請檢查工程中,是否在後臺執行緒(非主執行緒)呼叫 AppKit、UIKit相關的API,比如iOS 10+ 請求通知許可權時,[application registerForRemoteNotifications];在回撥非主執行緒中執行,則Xcode 9會報上述錯誤。

  1. [_notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert
    |UNAuthorizationOptionBadge|UNAuthorizationOptionSound completionHandler:^(BOOL granted,NSError*_Nullable error){
  2. if(granted){
  3. // granted
  4. NSLog(@"User authored notification.");
  5. // 向APNs註冊,獲取deviceToken
  6. [application registerForRemoteNotifications];
  7. }else{
  8. // not granted
  9. NSLog(@"User denied notification.");
  10. }
  11. }];

應修改為:

  1. [_notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound completionHandler:^(BOOL granted,NSError*_Nullable error){
  2. if(granted){
  3. // granted
  4. NSLog(@"User authored notification.");
  5. // 向APNs註冊,獲取deviceToken
  6. dispatch_async(dispatch_get_main_queue
    (),^{
  7. [application registerForRemoteNotifications];
  8. };
  9. }else{
  10. // not granted
  11. NSLog(@"User denied notification.");
  12. }
  13. }];