SDK 설치 및 API 적용

SDK 설치

Cocoapod에서 SDK 다운로드

XCode 프로젝트 파일중 Podfile 파일에 다음과 같이 SDK를 추가합니다

pod 'RW'

기존에 SDK를 한번 설치한 경우에는 설치할SDK 버전을 표시해야 하는 경우도 있습니다. 아래와 같이 설치할 SDK버전을 명시적으로 표시하면 됩니다.

pod 'RW', '~> 1.1.49'

Terminal

Podfile 에 해당라인을 추가한 후 Terminal 프로그램을 실행하여 다음의 명령을 수행합니다.

pod install

SDK 버전 업데이트의 경우 다음의 명령을 수행합니다.

pod update

정상적으로 설치가 되면 아래와 같은 폴더 구조를 확인할 수 있습니다.

dotAuthorizationKey 등록

info.plist

info.plist 파일을 Open As Source Code 방식으로 오픈한 후, 아래 코드를 추가합니다. 추가한 코드 중 4번 라인 serviceNumber의 string value를 올바른 값으로 변경해야 합니다.

...
<!--
  // =======================================================
  // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
  // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
  // =======================================================
-->
<key>dotAuthorizationKey</key>
<dict>
    <key>serviceNumber</key>
    <string>xxxxx</string>
    <key>expireDate</key>
    <string>14</string>
    <key>isDebug</key>
    <string>true</string>
    <key>isInstallRetention</key>
    <string>true</string>
    <key>isFingerPrint</key>
    <string>true</string>
    <key>accessToken</key>
    <string></string>
    <key>useMode</key>
    <string>2</string>
</dict>
...

  대시보드 화면 좌측 메뉴에서 "서비스 설정 > 어플리케이션 설정"화면에서 "서비스 번호"를 복사하여

info.plist 파일 4번 라인 serviceNumber의 string value로 입력해주세요.

HTTP 통신 허용

info.plist

http통신을 허용하기 위해 NSAppTransportSecurity 를 아래와 같이 추가합니다

...
<!--
  // =======================================================
  // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
  // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
  // =======================================================
-->
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
...

"Push Notification" Capability 추가

앱에 푸시기능을 추가합니다.

"Signing & Capabilities" 탭을 선택한 후 화면 왼쪽의 "+ Capability"를 눌러주세요.

"Capability"화면에서 "Push Notification"기능을 선택합니다.

이제 "Push Notification" 기능이 활성화되었습니다.

초기화

  • 초기화 방법은 SceneDelegate 가 설정된 경우와 설정되지 않은 경우에 따라 달라집니다.

  • SceneDelegate를 사용하지 않으면 AppDelegate에서 초기화작업을 하고, 그렇지 않고 SceneDelegate를 사용하면 SceneDelegate에서 이 작업을 해야 합니다.

1. iOS13 미만 (SceneDelegate 없음)

AppDelegate의 didFinishLaunchingWithOptions 함수에 SDK를 Initialization하기 위한 코드를 다음과 같이 적용합니다. SDK가 정상적으로 초기화 되었을 때 아래와 같은 기본 분석이 가능합니다.

  • 앱 실행 및 방문수, 일/주/월순수방문수 등 방문과 관련된 지표

  • 통신사, 단말기, 국가 등 방문자의 단말기 환경으로 부터 추출될 수 있는 지표

import DOT

// =======================================================
// AppDelegate에 "UNUserNotificationCenterDelegate" 프로토콜이 선언되어야 합니다.
// =======================================================
@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
  ...
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // =======================================================
    // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
    // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
    // =======================================================
    // Start : Wisetracker SDK 호출
    DOT.initialization(launchOptions, application: application)
    #if DEBUG
      DOT.checkDebugMode(true)
    #else
      DOT.checkDebugMode(false)
    #endif
    // End : Wisetracker SDK init
  }
  ...
}

DOT가 사용되는 곳에서는 import DOT을 통해 import가 필요합니다. 이하 적용 예시에서는 import하는 부분이 생략되어 있습니다.

2. iOS13 이상 (SceneDelegate 사용)

👉 iOS13 이상이어도 SceneDelegate를 사용하지 않을 수도 있어요, 이 때에는 위의 SceneDelegate를 사용하지 않는 경우를 참조하세요.

SceneDelegatesceneDidBecomeActive함수에 SDK를 Initialization하기 위한 코드를 다음과 같이 적용합니다. SDK가 정상적으로 초기화 되었을 때 아래와 같은 기본 분석이 가능합니다.

  • 앱 실행 및 방문수, 일/주/월순수방문수 등 방문과 관련된 지표

  • 통신사, 단말기, 국가 등 방문자의 단말기 환경으로 부터 추출될 수 있는 지표

import DOT

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
...
  func sceneDidBecomeActive(_ scene: UIScene) {
    // =======================================================
    // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
    // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
    // =======================================================
    // Start : Wisetracker SDK 호출
    DOT.initialization(nil, application: UIApplication.shared)
    #if DEBUG
      DOT.checkDebugMode(true)
    #else
      DOT.checkDebugMode(false)
    #endif
    // End : Wisetracker SDK 호출
  }
...
}sw

PushMessage API 적용(필수)

Device Token 등록

Wisetracker SDK 호출 한 코드 아래에 푸시 권한을 요청하는 코드를 삽입합니다.

// iOS10 부터 UNUserNotification 을 사용하여 서비스 등록 및 처리 방법이 변경되었기 때문에 
// iOS10 버전과 하위버전을 같이 처리할 수 있도록 적용이 필요합니다.
// interface에 UNUserNotificationCenterDelegate 도 추가 해 주세요.
#import <RCTAppDelegate.h>
#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate : RCTAppDelegate<UIApplicationDelegate,UNUserNotificationCenterDelegate>

@end
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
  ...
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // =======================================================
    // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
    // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
    // =======================================================
    // Start : Wisetracker SDK 호출
    DOT.initialization(launchOptions, application: application)
    #if DEBUG
      DOT.checkDebugMode(true)
    #else
      DOT.checkDebugMode(false)
    #endif
    // End : Wisetracker SDK init
    ...
    // =======================================================
    // Start : 푸시 권한 요청 <-- 새로 추가된 부분 (1/2)
    // =======================================================
    registerForRemoteNotifications() 
    // =======================================================
    // End : 푸시 권한 요청
    // =======================================================
    ...
  }
  ...
  // =======================================================
  // Start : 푸시 권한 요청 <-- 새로 추가된 부분 (2/2)
  // =======================================================
  // MARK: PushMessage: Regist
  private func registerForRemoteNotifications() {
    // 권한 요청
    let center = UNUserNotificationCenter.current()
    center.delegate = self // push처리에 대한 delegate - UNUserNotificationCenterDelegate
    let options: UNAuthorizationOptions = [.alert, .sound, .badge]
    center.requestAuthorization(options: options) { (granted, error) in
      guard granted else {
        return
      }
      DispatchQueue.main.async {
        UIApplication.shared.registerForRemoteNotifications()
      }
    }
  }
  // =======================================================
  // End : 푸시 권한 요청
  // =======================================================
}

Device Token 수집

Device token은 푸시 발송 시스템에서 메시지 전송시 수신 대상이 되는 개개인 별로 Unique하게 발급되는 일종의 식별ID 값입니다. Device token을 수집을 위해서 AppDelegate 에 정의된 didRegisterForRemoteNotificationsWithDeviceToken() 함수에 아래와 같이 분석 코드를 적용합니다

AppDelegate

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
  ...
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // =======================================================
    // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
    // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
    // =======================================================
    // Start : Wisetracker SDK 호출
    DOT.initialization(launchOptions, application: application)
    #if DEBUG
      DOT.checkDebugMode(true)
    #else
      DOT.checkDebugMode(false)
    #endif
    // End : Wisetracker SDK init
    ...
    // =======================================================
    // Start : 푸시 권한 요청
    // =======================================================
    registerForRemoteNotifications() 
    // =======================================================
    // End : 푸시 권한 요청
    // =======================================================
    ...
  }
  ...
  // =======================================================
  // Start : 푸시 권한 요청
  // =======================================================
  // MARK: PushMessage: Regist
  private func registerForRemoteNotifications() {
    // 권한 요청
    let center = UNUserNotificationCenter.current()
    center.delegate = self // push처리에 대한 delegate - UNUserNotificationCenterDelegate
    let options: UNAuthorizationOptions = [.alert, .sound, .badge]
    center.requestAuthorization(options: options) { (granted, error) in
      guard granted else {
        return
      }
      DispatchQueue.main.async {
        UIApplication.shared.registerForRemoteNotifications()
      }
    }
  }
  // =======================================================
  // End : 푸시 권한 요청
  // =======================================================
  
  // =======================================================
  // Start : 푸시 토큰 등록 <-- 새로 추가된 부분
  // =======================================================
  func application(_ application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    ...
    let tokenParts = deviceToken.map { data -> String in
      return String(format: "%02.2hhx", data)
    }
    let token = tokenParts.joined()
    DOT.setPushToken(token)
    ...
  }
  // =======================================================
  // End : 푸시 토큰 등록
  // =======================================================
}

푸시메세지 클릭 측정

  • 수신된 푸시 메시지를 클릭하여 앱이 실행된 오픈수 분석을 위하여 아래와 같이 추가합니다.

AppDelegate

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
  ...
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // =======================================================
    // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
    // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
    // =======================================================
    // Start : Wisetracker SDK 호출
    DOT.initialization(launchOptions, application: application)
    #if DEBUG
      DOT.checkDebugMode(true)
    #else
      DOT.checkDebugMode(false)
    #endif
    // End : Wisetracker SDK init
    ...
    // =======================================================
    // Start : 푸시 권한 요청
    // =======================================================
    registerForRemoteNotifications() 
    // =======================================================
    // End : 푸시 권한 요청
    // =======================================================
    ...
  }
  ...
  // =======================================================
  // Start : 푸시 권한 요청
  // =======================================================
  // MARK: PushMessage: Regist
  private func registerForRemoteNotifications() {
    // 권한 요청
    let center = UNUserNotificationCenter.current()
    center.delegate = self // push처리에 대한 delegate - UNUserNotificationCenterDelegate
    let options: UNAuthorizationOptions = [.alert, .sound, .badge]
    center.requestAuthorization(options: options) { (granted, error) in
      guard granted else {
        return
      }
      DispatchQueue.main.async {
        UIApplication.shared.registerForRemoteNotifications()
      }
    }
  }
  // =======================================================
  // End : 푸시 권한 요청
  // =======================================================
  
  // =======================================================
  // Start : 푸시 토큰 등록
  // =======================================================
  func application(_ application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    ...
    let tokenParts = deviceToken.map { data -> String in
      return String(format: "%02.2hhx", data)
    }
    let token = tokenParts.joined()
    DOT.setPushToken(token)
    ...
  }
  // =======================================================
  // End : 푸시 토큰 등록
  // =======================================================
  
  // =======================================================
  // Start : 푸시 클릭 <-- 새롭게 추가된 부분
  // =======================================================
  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    ...
    DOT.setPushClick(response.notification.request.content.userInfo, application: UIApplication.shared)
    ...
    completionHandler()
  }
  // =======================================================
  // End : 푸시 클릭
  // =======================================================
}

이미지 푸시메시지 적용(선택)

Notification Service Extension Target 추가

이미지를 포함한 푸시메세를 수신받기 위해 필요합니다.

File - New - Target 메뉴에서 "Notification Service Extension"을 선택합니다.

Product Name에 타겟명을 입력합니다. (아래에서 Podfile에 target을 추가할때 사용할 타겟명입니다)

Finish 버튼 클릭 후 아래와 같은 NotificationServiceExtension 폴더가 생성됩니다.

Podfile 수정

Podfile에 아래와 같이 이미지 푸시를 위한 타겟을 추가한 후 pod install 명령어를 실행시켜 줍니다.

Podfile

target 'wisetracker' do
  ...
  # S: Wisetracker SDK add
  pod 'RW'
  # E: Wisetracker SDK add
  ...
end
...

# =======================================================
# Start : 이미지 푸시를 위한 추가
# =======================================================
target 'NotificationServiceExtension' do
  use_frameworks!
  ### 만약 Wisetracker SDK 의 버전이 명시되어 있는 경우 동일하게 버전을 명시 해 주세요.
  pod 'RW'
end
# =======================================================
# End : 이미지 푸시
# =======================================================
...
...

위의 "NotificationServiceExtension"은 고객사에서 만든 타켓명으로 해주셔야 합니다.

예시는 타겟명이 "NotificationServiceExtension"인 경우입니다.

NotificationService 수정

  • NotificationService 파일을 열어 아래의 내용으로 대체해 주세요. * 기존 내용을 모두 삭제하고 아래 내용으로 대체하는것이며, 추가가 아님에 유의 해 주세요.

NotificationService

// =======================================================
// Start : 소스코드 모두 바꾸기
// =======================================================
import UserNotifications
import DOT
class NotificationService: UNNotificationServiceExtension {
    var contentHandler: ((UNNotificationContent) -> Void)?
    var receivedRequest: UNNotificationRequest!
    var bestAttemptContent: UNMutableNotificationContent!
    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.receivedRequest = request
        self.contentHandler = contentHandler
        self.bestAttemptContent = DOT.didReceiveNotificationExtensionRequest(request, with: bestAttemptContent)
        if let bestAttemptContent = self.bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}
// =======================================================
// End : 소스코드 모두 바꾸기
// =======================================================

동영상 Push 적용(선택)

Notification Content Extension Target 추가

동영상을 포함한 Push를 확장했을 때 Push 화면영역 내에서 동영상 실행을 위해 필요합니다.

File - New - Target 메뉴에서 Notification Content Extension 선택합니다.

Product Name에 타겟명을 입력합니다. (아래에서 Podfile에 target을 추가할때 사용할 타겟명입니다)

추가 완료 시 아래와 같은 폴더가 생성됩니다.

기존파일 대체

이 작업은 파인더를 이용해서 진행해주세요, XCode에서 복사/붙여넣기 하면 제대로 복사되지 않습니다

Pods/RW/Resources 경로 아래 Base.lproj 폴더와, NotificationViewController 파일을 복사하여, 새로 생성한 NotificationContentExtension 폴더의 동일한 파일에 덮어 씌워 줍니다.

info.plist 파일 수정

NSExtensionAttributes 키값을 찾아 아래와 같이 replace해줍니다.

info.plist

...
<!--
=======================================================
Start : 동영상 푸시 
=======================================================
-->
<key>NSExtensionAttributes</key>
<dict>
    <key>UNNotificationExtensionCategory</key>
    <array>
        <string>RWVideoPush</string>
    </array>
    <key>UNNotificationExtensionDefaultContentHidden</key>
    <false/>
    <key>UNNotificationExtensionInitialContentSizeRatio</key>
    <real>0.4</real>
    <key>UNNotificationExtensionOverridesDefaultTitle</key>
    <false/>
    <key>UNNotificationExtensionUserInteractionEnabled</key>
    <false/>
</dict>
<!--
=======================================================
End : 동영상 푸시
=======================================================
-->
...

Podfile 수정

아래와 같이 YouTubePlayer 라이브러리(동영상 실행을 위한 라이브러리)를 추가하고, pod install를 실행합니다.

아래의 "NotificationContentExtension"은 고객사에서 만든 타켓명으로 해주셔야 합니다. 예시는 타겟명이 "NotificationContentExtension"인 경우입니다.

Podfile

...
target 'wisetracker' do
  ...
  # S: Wisetracker SDK add
  pod 'RW'
  pod 'Firebase/Messaging'
  # E: Wisetracker SDK add
  ...
end
...

# =======================================================
# Start : 동영상 푸시 
# =======================================================
target 'NotificationContentExtension' do
  pod 'YouTubePlayer'
end
# =======================================================
# End : 동영상 푸시
# =======================================================
...

푸시 수신동의

푸시발송은 기본 적용에서는 "수신거부"입니다. 아래 링크를 참조하여 화면에서 수신동의/거부를 진행 후 해당 데이터를 "태깅"작업을 통해 남겨주세요.

축하합니다.

이제 iOS SDK 설정이 완료되었습니다.

Last updated