program tip

UIApplication.registerForRemoteNotifications ()는 메인 스레드에서만 호출되어야합니다.

radiobox 2020. 10. 28. 07:58
반응형

UIApplication.registerForRemoteNotifications ()는 메인 스레드에서만 호출되어야합니다.


푸시 (원격) 알림을 등록하는 동안 오류 / 경고를 표시하는 Xcode 9 (iOS 11).

다음은 오류 메시지입니다.

여기에 이미지 설명 입력

그리고 여기에 코드가 있습니다.

let center  = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
        if error == nil{
              UIApplication.shared.registerForRemoteNotifications()
        }
 }

오류 / 경고 라인 :

UIApplication.shared.registerForRemoteNotifications ()

이 문제를 해결하는 방법?


에서 swift4

이 문제는 다음과 같이 해결할 수 있습니다.

DispatchQueue.main.async(execute: {
  UIApplication.shared.registerForRemoteNotifications()
}) 

이것이 도움이되기를 바랍니다 ...


Objective C의 경우 아래 코드가 작동합니다.

    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    });

요약 :
모든 UI 조작은 문제를 방지하기 위해 메인 스레드에서 수행되어야합니다. 그렇게하지 않으면 메인 스레드 검사기 (XCode 9에서 새로 도입 된 디버깅 기능)가 런타임에 문제를 생성합니다. 따라서 결함과 런타임 경고를 피하기 위해 아래와 같이 Main Thread 블록에 코드를 래핑하십시오.

DispatchQueue.main.async {
    UIApplication.shared.registerForRemoteNotifications()
}

버전 이전의 Xcode 릴리스에서. 9에서는 메인 스레드와 관련된 경고가 콘솔 영역에 텍스트로 인쇄됩니다. 어쨌든 Edit SchemeDiagnostic 설정에서 Main Thread Checker를 선택적으로 비활성화 ( 권장되지 않는 방법 ) 할 수 있습니다 .


설명:

Apple은 UIKit 및 UI 요소를 조작하는 기타 API에 대한 런타임에서 문제를 확인하기 위해 XCode 9에 새로운 디버깅 옵션을 도입했습니다. 주 스레드 블록없이 런타임에 UIKit API에서 UI 요소가 변경되면 UI 결함 및 충돌이 발생할 가능성이 높습니다. 주 스레드 검사기는 런타임에 이러한 문제를 잡기 위해 기본적으로 활성화되어 있습니다. 실제로 권장하지는 않지만 아래와 같이 Edit Scheme에서 Main Thread Checker비활성화 할 수 있습니다 .

주 스레드 검사기 비활성화

If you have any older SDK's or Frameworks, when updating to Xcode 9, you may face this warning since some of the UIKit method calls wouldn't have been wrapped in Main Thread. Updating them to latest version would fix the issue (if the developer is aware of it and fixed it).

Quote from XCode 9 beta release notes:

  • New in Xcode 9 – Main Thread Checker.
    • Enable detection of UI API misuse from background thread
    • Detects AppKit, UIKit, and WebKit method calls that are not made on the main thread.
    • Automatically enabled during debugging, and can be disabled in the Diagnostic tab of the scheme editor.
    • Main Thread Checker works with Swift and C languages.

The error message is pretty clear: dispatch registerForRemoteNotifications to the main thread.

I would use the granted parameter and handle the error accordingly

center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
        if granted {
              DispatchQueue.main.async {
                  UIApplication.shared.registerForRemoteNotifications()
              }
        } else {
           print(error!)
           // handle the error
        }
}

이것은 또한 Swift 4.0 에서 수행하는 올바른 방법입니다.

UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge], completionHandler: {(granted,error) in
            if granted{
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
        })

이것이 도움이되기를 바랍니다.

DispatchQueue.main.async(execute: {
  UIApplication.shared.registerForRemoteNotifications()
})

이것이 나를 위해 일한 것입니다. 위의 허용 된 주석에서 @ Mason11987의 의례.

DispatchQueue.main.async() { code }

참고 URL : https://stackoverflow.com/questions/44391367/uiapplication-registerforremotenotifications-must-be-called-from-main-thread-o

반응형