ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [iOS] APNs 뜯어보기(3) - 호출 순서
    ios/ios 2023. 11. 17. 17:18

     

     

    APNs의 호출순서는 아래 그림과 같습니다.

    이 호출 순서를 코드로 확인해 보겠습니다.

     

    1. 권한 요청, 디바이스 토큰 요청

    apple은 디바이스에서 어떤 기능을 사용하려고 하면 사용자에게 권한을 요청합니다. 푸시 알림도 사용자에게 권한을 요청해야만 푸시알림을 받을 수 있습니다. 먼저 디바이스 토큰을 얻기 전에  UNUserNotificationCenter에 있는 메소드인 requestAuthorization()을 사용해서 권한을 요청할 수 있습니다. 

     

    매개변수인 options에는 6가지의 옵션을 넣을 수 있습니다.

    • alert : 푸시 알림
    • sound : 알림을 받을 때의 소리
    • badge : 알림이 왔을 때 앱 아이콘 오른쪽 상단에 나타나는 숫자
    • carplay : carplay 환경에서 알림을 표시하는 기능
    • criticalAlert : 중요한 경고에 대한 소리를 재생하는 기능
    • providesAppNotificationSettings : 앱 안에서 Notification 설정 버튼을 표시해야하는 옵션?
    • provisional : 권한 요청을 묻지 않고 푸시 알림을 받을 수 있지만 소리나 베너로 나타나지 않고 아이폰의 알림 센터의 기록에만 나타나는 기능

    앱에서 필요한 옵션들을 정해서 권한을 요청하면 completionHandler에서 true나 false값으로 권한 수락 여부를 알 수 있습니다. 

     

    권한이 수락되었다면 UIApplication.shared.registerForRemoteNotifications()으로 디바이스토큰을 등록할 수 있습니다. 아래 코드처럼 사용할 수 있습니다.

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge, .carPlay, .criticalAlert, .providesAppNotificationSettings]) { granted, error in
    	if granted {
    		DispathcQueue.main.async {
    			UIApplication.shared.registerForRemoteNotifications()
    		}
    	}
    }

     

     

    2. 디바이스 토큰을 저장

    디바이스 토큰이 있어야지만 서버에서 APNs를 통해 내 디바이스에 푸시 알림을 보낼 수 있습니다. 디바이스 토큰은 didRegisterForeRemoteNotificationWithDeviceToken을 통해서 받을 수 있습니다.

     

     

    처음에 반환되는 디바이스 토큰은 바이너리 값으로 반환됩니다. 서버에서 푸시알림을 보낼때 사용하는 디바이스 토큰은 16진수 디바이스 토큰을 사용하기 때문에 변환해 줘야 합니다. 아래 코드처럼 변환을 할 수 있습니다.

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            var token: String = ""
            for i in 0..<deviceToken.count {
                token += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
            }
            print("바이너리 디바이스 토큰", deviceToken.base64EncodedString())
            print("16진수 디바이스 토큰", token)
    }

    토큰 print결과

     

    3. 푸시알림 수신

    사전 준비가 완료되고 서버에서 푸시알림을 수신 하면 userNotificationCenter의 willPresent 메서드가 호출됩니다.

     

     

    4. 푸시알림 선택

    수신받은 푸시알림을 클릭하면 UNUserNotificationCenter의 didReceive 메서드가 호출됩니다.

     

     

     

    참고

    https://developer.apple.com/documentation/usernotifications/unusernotificationcenter

     

    UNUserNotificationCenter | Apple Developer Documentation

    The central object for managing notification-related activities for your app or app extension.

    developer.apple.com

     

     

     

Designed by Tistory.