iOS 푸시 메시지 연동

📘

타 푸시 솔루션과 함께 사용할 수 있습니다

타 푸시 솔루션과 함께 사용하려면 타 푸시 솔루션의 Swizzling 옵션을 비활성화해야 합니다.

Swizzling 비활성화 후, 해당 솔루션의 가이드를 참고하여 푸시 알림 처리를 수동으로 설정해 주세요.


1. APNs 설정하기

iOS 앱에서 푸시 메시지를 사용하기 위해서는 핵클 워크스페이스와 APNs 연동 설정이 필요합니다.

자세한 내용은 Apple Push Notification Service 설정을 참고하세요.

2. 앱에 PushNotification Capability 추가

Xcode로 /ios/{APP_NAME}.xcworkspace 파일을 열어 프로젝트를 연 후 프로젝트 설정의 Signing & Capabilities 탭에서 + Capability를 아래와 같이 클릭해주세요.

Push NotificationsBackground Modes를 추가해주세요.

그리고 Background ModesRemote notifications를 활성화해 주세요.

3. 핵클 SDK와 연동하기

푸시 메시지 연동을 위해서는 AppDelegate 수정이 필요합니다.

Xcode로 /ios/{APP_NAME}.xcworkspace 파일을 열어 프로젝트를 연 후 AppDelegate 파일을 엽니다.

📘

AppDelegate 파일은 React Native 버전별로 언어가 다릅니다.

  • React Native 0.77 이상 AppDelegate.swift
  • React Native 0.76 이하 AppDelegate.h & AppDelegate.mm

푸시 토큰 수집

AppDelegate에 아래과 같이 setPushToken 메소드를 추가합니다.

import UIKit
import React
import React_RCTAppDelegate
import ReactAppDependencyProvider
import Hackle

@main
class AppDelegate: RCTAppDelegate {
  override func application(
    _ application: UIApplication, 
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
  ) -> Bool {
    // 기존 구현된 코드 내에 추가
    ...
  	
    // iOS 앱에서 푸시 권한 요청
    let notificationCenter = UNUserNotificationCenter.current()
    notificationCenter.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
    }
    notificationCenter.delegate = self
    application.registerForRemoteNotifications()

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
  override func application(
    _ application: UIApplication, 
    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
  ) {
    // 핵클 서버로 APNs 푸시 토큰 전달
    Hackle.setPushToken(deviceToken)
  }
...
}
#import <RCTAppDelegate.h>
#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate : RCTAppDelegate <UIApplicationDelegate, UNUserNotificationCenterDelegate>

@end
#import "AppDelegate.h"
#import <Hackle/HackleNotification.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  ...
  // 기존 구현된 코드 내에 추가
  UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
  [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {}];
  center.delegate = self;
  [[UIApplication sharedApplication] registerForRemoteNotifications];  
  ...
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  [HackleNotification setPushToken:deviceToken];
}

푸시 메시지 표시

포그라운드 푸시 메시지 표시

포그라운드 푸시 메시지 표시를 위해 userNotificationCenter 메소드를 추가합니다.

import Hackle

extension AppDelegate: UNUserNotificationCenterDelegate {
  // Foreground push message
  func userNotificationCenter(
    _ center: UNUserNotificationCenter, 
    willPresent notification: UNNotification, 
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions
  ) -> Void) {
    
    if Hackle.userNotificationCenter(
      center: center, willPresent: notification, withCompletionHandler: completionHandler
    ) {
      // Succefully processed notification
      // Automatically consumed completion handler
      return
    } else {
      // Received not hackle notification or error
      print("Do something")
      
      if #available(iOS 14.0, *) {
        completionHandler([.list, .banner])
      } else {
        completionHandler([.alert])
      }
    }
  }
}
// Foreground push message
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
    if ([Hackle userNotificationCenterWithCenter:center
                                      willPresent:notification
                             withCompletionHandler:completionHandler]) {
        // Succefully processed notification
        // Automatically consumed completion handler
        return;
    } else {
        // Received not hackle notification or error
        NSLog(@"Do something");
        completionHandler(UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner);
    }
}

핵클에서 송신한 푸시가 아닌 경우 false가 리턴됩니다.


푸시 클릭 처리

푸시 클릭 처리를 위해 handleNotification 메소드를 추가합니다.

❗️

핵클에서 제공하는 푸시 클릭 처리 함수를 호출하지 않으면 푸시가 정상적으로 처리되지 않습니다.

또한, 푸시 클릭 이벤트가 수집되지 않고 푸시 클릭률 지표를 이용할 수 없습니다.

import Hackle

extension AppDelegate: UNUserNotificationCenterDelegate {
  // push click
  public func userNotificationCenter(
    _ center: UNUserNotificationCenter, 
    didReceive response: UNNotificationResponse, 
    withCompletionHandler completionHandler: @escaping () -> Void
  ) {
    
    if let _ = Hackle.handleNotification(response: response) {
      // process hackle notification
    } else {
      // not hackle notification or error
      print("do something")
    }
    
    // handleNotification 에서 completionHandler를 호출하지 않으니 
    // 핵클 푸시 여부에 관계없이 반드시 completionHandler를 호출해야 합니다.
    completionHandler()
  }
}
// push click
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler
{
    if ([Hackle handleNotificationWithResponse:response] != nil) {
        // process hackle notification
    } else {
        // not hackle notification or error
        NSLog(@"do something");
    }
    // handleNotification 에서 completionHandler를 호출하지 않으니 
    // 핵클 푸시 여부에 관계없이 반드시 completionHandler를 호출해야 합니다.
    completionHandler();
}

푸시 클릭 함수는 아래 순서로 처리를 합니다.

  1. 핵클에서 송신한 푸시인지 확인
  2. 푸시 클릭 이벤트를 핵클 서버로 송신
  3. (deep link push인 경우) deep link 처리

핵클에서 송신한 푸시가 아닌 경우 nil이 리턴됩니다.


4. 푸시 메시지 테스트

토큰 확인

사용자 식별자 확인하기 가이드 를 통해 iOS 기기에 설정된 토큰을 확인합니다.

테스트

푸시 메시지 테스트 발송 가이드 를 참고하여 푸시 메시지를 iOS 기기에서 확인합니다.


(Advanced) 딥링크 이동

핵클 푸시 메시지는 클릭 시 딥링크 이동을 지원합니다.

iOS 환경에서 React Native 딥링크를 사용하는 방법은 React Native 딥링크 가이드 에서 확인 가능합니다.

🚧

원격 JS 디버거에 연결된 경우 React Native의 Linking.getInitialURL()null이 리턴되어 딥링크로 연결 될 링크를 확인 못하는 문제가 있습니다.



(Advanced) iOS 이미지를 포함한 푸시 메시지 표시 (Rich Push Notification)

iOS 앱에서 이미지를 포함한 푸시 메시지를 보여주기 위해서는 Notification Service Extension을 추가하여 아래의 설정을 완료합니다.

Hackle iOS Rich Push Notification 설정 가이드

iOS Rich Push Notification 에 대한 자세한 사항은 Rich Push Notification 에서 확인 가능합니다.