Swift ) requestAuthorization, registerForRemoteNotifications - EEYatHo iOS
요약 : 알람 설정 관련 코드들 특성을 분석해서 아래 코드 완성
// 최초 1번만 실행해도 괜찮음.
// 계속 실행해도 괜찮지만, 팝업은 안뜨고 completion은 매번 실행됨.
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound], completionHandler: { (granted, error) in
print("requestAuthorization granted = \(granted)")
if let e = error {
print("error = \(e)")
}
})
// 매번 실행하기. 디바이스 토큰이 언제 바뀔지 모름.
// 팝업이 뜨거나 하지 않음. 델리게이트로 APNS서버에 등록된 디바이스 토큰값 확인 가능.
UNUserNotificationCenter.current().delegate = self
UIApplication.shared.registerForRemoteNotifications()
[ requestAuthorization ]
시스템 팝업 띄우면서, 유저한테 알람 권한 물어보기
[ 특성 ]
시스템 팝업은 최초 한번만 노출되며, 그 이후엔 뜨지않음.
하지만 completionHandler는 팝업 노출과 관계없이 계속 실행됨.
이 알람 권한은 로컬 알람, 원격 푸시 알람 다 포함됨.
앱 실행시마다 매번 실행 or 최초 한번만 실행
[ 선언문과 구현 코드 ]
open func requestAuthorization(options: UNAuthorizationOptions = [], completionHandler: @escaping (Bool, Error?) -> Void)
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound], completionHandler: { (granted, error) in
print("requestAuthorization granted = \(granted)")
if let e = error {
print("error = \(e)")
}
})
[ registerForRemoteNotifications ]
원격 푸시에 필요한 정보(디바이스 토큰)를 APNS서버에 등록함.
결과에 따라 아래 델리게이트 함수들을 호출.
didRegisterForRemoteNotificationsWithDeviceToken
didFailToRegisterForRemoteNotificationsWithError << 주로 시뮬레이터에서 발생
[ 특성 ]
희안한 특성들이 있음.. 공식 문서에 정리좀 제발.. 애플아 제발
1) 앱이 설치된 후, 한번이라도 requestAuthorization 이 호출 된 이후에만 작동함.
2) requestAuthorization -> 앱 종료 -> 앱 실행 -> registerForRemoteNotifications 해도 정상작동. (delegate 함수 호출 함)
3) requestAuthorization 로 팝업을 띄운 직후, 권한을 아직 고르지 않은 상태에서 registerForRemoteNotifications 해버려도, 권한 고르면 정상작동.
4) 앱이 종료되지 않았다면 순서가 바뀌어도 괜찮음. (registerForRemoteNotifications -> 권한 선택 -> 앱을 종료하지 않고 requestAuthorization 여도 정상작동.)
그래서 얘는 언제 실행해줘야 하는가?
리서칭 한 결과, 토큰이 언제 바뀔지 모른다는 이유로 매번 실행해줘야함.
[ 재실행 / 알람권한 끄고 재실행 / 알람권한 끄고 다시 켜고 재실행 ]
다 해봐도, didRegisterForRemoteNotificationsWithDeviceToken 로 떨어지는 디바이스 토큰이 안바뀌던데.. ( 물론 앱 재설치하면 바뀜. )
앱 실행시마다 등록한다고 해서 크게 나쁘지 않고, 토큰이 변경되는 명확한 조건은 모르니.. 매번 등록하기로 결정.
[ 선언문과 구현 코드 ]
@available(iOS 8.0, *)
open func registerForRemoteNotifications()
UIApplication.shared.registerForRemoteNotifications()
Finally, 두 종류의 알람 설정 코드의 특성을 파악한 결과, 아래 코드 완성.
// 최초 1번만 실행해도 괜찮음.
// 계속 실행해도 괜찮지만, 팝업은 안뜨고 completion은 매번 실행됨.
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound], completionHandler: { (granted, error) in
print("requestAuthorization granted = \(granted)")
if let e = error {
print("error = \(e)")
}
})
// 매번 실행하기. 디바이스 토큰이 언제 바뀔지 모름.
// 팝업이 뜨거나 하지 않음. 델리게이트로 APNS서버에 등록된 디바이스 토큰값 확인 가능.
UNUserNotificationCenter.current().delegate = self
UIApplication.shared.registerForRemoteNotifications()