Programming/iOS

[iOS/Swift] APNs (Apple Push Notifications) 알아보기, 사용법

devssun 2017. 8. 3. 20:30
728x90
반응형

APNs (Apple Push Notifications)


  • APNs는 애플에서 제공하는 푸시 서버로 써드파티의 서버에서 APNS서버로 메시지를 보내면 APNS에서 해당 디바이스에 직접적으로 메시지를 전달한다

APNs 구현 단계

  1. 개발자 계정, 인증서 셋팅 (https://developer.apple.com)
  2. 인증서 요청 생성 (키체인 접근 > 인증서 지원 > 인증기관에서 인증서 요청)
    • 개발자 Apple ID 등록 필요(비용 발생)
    • APNs 인증서 발급, 서버용 APNs 인증서 발급
    • push notification 설정
    • Provisioning Profile 설정
  3. AppDelegate.swift 수정
    • 프로젝트에서 알림 허용하기
      • Project 설정 > Capabilities > Push notifications ON, Background Modes ON(Remote Notification)
    • 알림 허용 소스 코드
       func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
             // Override point for customization after application launch.
             /**************************** Push service start *****************************/
             // iOS 10 support
             if #available(iOS 10, *) {
                 let center = UNUserNotificationCenter.current()
                 center.requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
                 application.registerForRemoteNotifications()
             }
             /***************************** Push service end ******************************/
             print("didFinishLaunchingWithOptions")
             return true
         }
  • 토큰 가져오기

    // Called when APNs has assigned the device a unique token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // Convert token to string
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
     
        // Print it to console
        print("APNs device token: \(deviceTokenString)")
     
        // Persist it in your backend in case it's new
    }
  • 알림 받았을 때 실행되는 메소드

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
  1. 서버를 위한 pem 파일 생성
  2. APNS 테스터를 통해 테스트 (App Store - Easy APNs Provider)

** APNS 메시지는 Device Token과 Payload로 구성됨
https://dinfree.github.io/apns_dinfree/#21gcm-서비스-구조---향후-보완


에러문구
but you still need to add "remote-notification" to the list of your supported UIBackgroundModes in your Info.plist.

  • Project 설정 > Capabilities > Push notifications ON, Background Modes ON(Remote Notification)


-- Markdown으로 작성한 게시글입니다

반응형