콘텐츠로 건너뛰기

iOS SDK 7.0+ 기본 통합 가이드

이 섹션에서는 Pushwoosh SDK를 iOS 애플리케이션에 통합하는 방법에 대한 정보를 제공합니다.

전제 조건

Anchor link to

Pushwoosh iOS SDK를 앱에 통합하려면 다음이 필요합니다:

통합 단계

Anchor link to

Swift Package Manager 또는 CocoaPods를 사용하여 Pushwoosh SDK를 애플리케이션에 통합할 수 있습니다.

Swift Package Manager

Anchor link to

Package Dependencies 섹션에서 다음 패키지를 추가합니다:

https://github.com/Pushwoosh/Pushwoosh-XCFramework

Pushwoosh iOS SDK를 사용하려면 Swift Package Manager를 통해 통합할 때 다음 네 가지 프레임워크를 앱 타겟에 추가해야 합니다:

  • PushwooshFramework
  • PushwooshCore
  • PushwooshBridge
  • PushwooshLiveActivities

Podfile을 열고 종속성을 추가합니다:

Terminal window
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'MyApp' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
pod 'PushwooshXCFramework'
end

그런 다음 터미널에서 다음 명령을 실행하여 종속성을 설치합니다:

Terminal window
pod install

2. Capabilities

Anchor link to

프로젝트에서 푸시 알림을 활성화하려면 특정 capability를 추가해야 합니다.

Signing & Capabilities 섹션에서 다음 capability를 추가합니다:

  • Push Notifications
  • Background Modes. 이 capability를 추가한 후 Remote notifications 확인란을 선택합니다.

Time Sensitive Notifications(iOS 15+)를 사용하려는 경우 Time Sensitive Notifications capability도 추가합니다.

3. 초기화 코드

Anchor link to

AppDelegate

Anchor link to

AppDelegate 클래스에 다음 코드를 추가합니다:

import SwiftUI
import PushwooshFramework
@main
struct MyApp: App {
// Register AppDelegate as UIApplicationDelegate
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate, PWMessagingDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Initialization code
// Set custom delegate for push handling
Pushwoosh.configure.delegate = self
// Register for push notifications
Pushwoosh.configure.registerForPushNotifications()
return true
}
// Handle token received from APNS
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Pushwoosh.configure.handlePushRegistration(deviceToken)
}
// Handle token receiving error
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
Pushwoosh.configure.handlePushRegistrationFailure(error)
}
//for silent push notifications
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
Pushwoosh.configure.handlePushReceived(userInfo)
completionHandler(.noData)
}
// Fired when a push is received
func pushwoosh(_ pushwoosh: Pushwoosh, onMessageReceived message: PWMessage) {
print("onMessageReceived: ", message.payload!.description)
}
// Fired when a user taps the notification
func pushwoosh(_ pushwoosh: Pushwoosh, onMessageOpened message: PWMessage) {
print("onMessageOpened: ", message.payload!.description)
}
}
struct ContentView: View {
var body: some View {
Text("Pushwoosh with SwiftUI")
.padding()
}
}

Info.plist

Anchor link to

Info.plist에서:

  • Pushwoosh_APPID 키를 Pushwoosh Application Code로 설정합니다.
  • Pushwoosh_API_TOKEN 키를 Pushwoosh Device API Token으로 설정합니다.

4. 메시지 전송 추적

Anchor link to

Pushwoosh는 Notification Service Extension을 통해 푸시 알림의 전송 이벤트를 추적하는 것을 지원합니다.

Notification Service Extension 추가

Anchor link to
  1. Xcode에서 File > New > **Target…**을 선택합니다.
  2. Notification Service Extension을 선택하고 Next를 누릅니다.
  3. 타겟 이름을 입력하고 Finish를 누릅니다.
  4. 활성화하라는 메시지가 나타나면 Cancel을 누릅니다.

Notification Service Extension의 종속성 (CocoaPods만 해당)

Anchor link to

참고: Swift Package Manager를 사용하여 종속성을 관리하는 경우 이 단계는 자동으로 추가되므로 건너뛸 수 있습니다.

Podfile을 열고 타겟에 대한 종속성을 추가합니다:

Podfile
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'MyApp' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
pod 'PushwooshXCFramework'
end
target 'MyAppNotificationExtension' do
use_frameworks!
pod 'PushwooshXCFramework'
end

터미널에서 다음 명령을 실행하여 종속성을 업데이트합니다:

Terminal window
pod update

Notification Service Extension에 Pushwoosh SDK 추가

Anchor link to

이 코드를 사용하면 알림 확장 프로그램 내에서 알림을 가로채고 처리할 수 있습니다.

import UserNotifications
import PushwooshFramework
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
// Pushwoosh **********
PWNotificationExtensionManager.shared().handle(request, contentHandler: contentHandler)
// ********************
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = bestAttemptContent {
// Modify the notification content here...
contentHandler(bestAttemptContent)
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}

Info.plist

Anchor link to

Notification Service Extension의 Info.plist에 다음을 추가합니다:

  • Pushwoosh_APPID - Application Code.

5. 프로젝트 실행

Anchor link to
  1. 프로젝트를 빌드하고 실행합니다.
  2. Pushwoosh Control Panel로 이동하여 푸시 알림을 보냅니다.
  3. 앱에서 알림을 볼 수 있습니다.

확장된 Pushwoosh iOS 통합

Anchor link to

이 단계에서는 이미 SDK를 통합했으며 푸시 알림을 보내고 받을 수 있습니다. 이제 핵심 기능을 살펴보겠습니다.

푸시 알림

Anchor link to

Pushwoosh SDK에는 푸시 알림 처리를 위해 설계된 두 가지 콜백이 있습니다:

  • onMessageReceived: 이 메서드는 푸시 알림을 수신할 때 호출됩니다.
  • onMessageOpened: 이 메서드는 사용자가 알림과 상호 작용(열기)할 때 호출됩니다.

이러한 콜백을 통해 개발자는 애플리케이션 내에서 푸시 알림의 수신 및 사용자 상호 작용을 관리할 수 있습니다.

import PushwooshFramework
class AppDelegate: NSObject, UIApplicationDelegate, PWMessagingDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
Pushwoosh.configure.delegate = self;
}
func pushwoosh(_ pushwoosh: Pushwoosh, onMessageOpened message: PWMessage) {
if let payload = message.payload {
print("onMessageOpened: \(payload)")
}
}
func pushwoosh(_ pushwoosh: Pushwoosh, onMessageReceived message: PWMessage) {
if let payload = message.payload {
print("onMessageReceived: \(payload)")
}
}
}

사용자 구성

Anchor link to

개별 사용자 행동 및 선호도에 초점을 맞춤으로써 개인화된 콘텐츠를 제공하여 사용자 만족도와 충성도를 높일 수 있습니다.

import PushwooshFramework
class Registration {
func afterUserLogin(user: User) {
let pushwoosh = Pushwoosh.configure
// set user ID
if let userId = user.userId {
pushwoosh.setUserId(userId)
}
// set user email
if let userEmail = user.email {
pushwoosh.setEmail(userEmail)
}
// set user SMS number
if let userSmsNumber = user.SmsNumber {
pushwoosh.registerSmsNumber(userSmsNumber)
}
// set user WhatsApp number
if let userWhatsAppNumber = user.WhatsAppNumber {
pushwoosh.registerSmsNumber(userWhatsAppNumber)
}
// setting additional user information as tags for Pushwoosh
if let age = user.userDetails.age,
let name = user.userDetails.userName,
let lastLogin = user.userDetails.lastLoginDate {
pushwoosh.setTags([
"age": age,
"name": name,
"last_login": lastLogin
])
}
}
}

태그는 사용자 또는 기기에 할당된 키-값 쌍으로, 선호도나 행동과 같은 속성을 기반으로 세분화하여 타겟 메시징을 가능하게 합니다.

import PushwooshFramework
class UpdateUser {
func afterUserUpdateProfile(user: User) {
let pushwoosh = Pushwoosh.configure
// set list of favorite categories
pushwoosh.setTags(["favorite_categories" : user.getFavoriteCategories()])
// set payment information
pushwoosh.setTags([
"is_subscribed": user.isSubscribed(),
"payment_status": user.getPaymentStatus(),
"billing_address": user.getBillingAddress()
])
}
}

이벤트는 앱 내에서 발생하는 특정 사용자 행동 또는 발생으로, 행동을 분석하고 해당 메시지나 작업을 트리거하기 위해 추적할 수 있습니다.

import PushwooshFramework
class Registration {
func afterUserLogin(user: User) {
if let userName = user.getUserName(), let lastLogin = user.getLastLoginDate() {
PWInAppManager.shared().postEvent("login", withAttributes: [
"name": userName,
"last_login": lastLogin
])
}
}
func afterUserPurchase(user: User, product: Product) {
let pushwoosh = Pushwoosh.configure
// Track purchase event
PWInAppManager.shared().postEvent("purchase", withAttributes: [
"product_id": product.getId(),
"product_name": product.getName(),
"price": product.getPrice(),
"quantity": product.getQuantity()
])
// Set user tags
let lastPurchaseDate = Date().timeIntervalSince1970
let lifetimeSpend = getCurrentLifetimeSpend() + product.getPrice()
pushwoosh.setTags([
"last_purchase_date": lastPurchaseDate,
"lifetime_spend": lifetimeSpend
])
}
}

리치 미디어

Anchor link to

리치 미디어는 사용자 참여를 향상시키기 위해 알림 및 인앱 메시지에 사용되는 이미지, 비디오 또는 HTML과 같은 대화형 멀티미디어 콘텐츠를 의미합니다.

import PushwooshFramework
class ViewController: UIViewController, PWRichMediaPresentingDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let richMediaConfiguration = PWModalWindowConfiguration.shared()
PWRichMediaManager.shared().delegate = self
richMediaConfiguration.configureModalWindow(with: .PWModalWindowPositionBottom,
present: .PWAnimationPresentFromBottom,
dismiss: .PWAnimationDismissDown)
}
func richMediaManager(_ richMediaManager: PWRichMediaManager!, shouldPresent richMedia: PWRichMedia!) -> Bool {
print("Rich media will be presented with: \(richMedia.pushPayload!)")
return true
}
func richMediaManager(_ richMediaManager: PWRichMediaManager!, didPresent richMedia: PWRichMedia!) {
print("Rich media has been presented with: \(richMedia.pushPayload!)")
}
func richMediaManager(_ richMediaManager: PWRichMediaManager!, didClose richMedia: PWRichMedia!) {
print("Rich media has been closed with: \(richMedia.pushPayload!)")
}
func richMediaManager(_ richMediaManager: PWRichMediaManager!, presentingDidFailFor richMedia: PWRichMedia!, withError error: (any Error)!) {
print("Failed to present rich media with: \(richMedia.pushPayload!). Error: \(error.localizedDescription)")
}
}

문제 해결

Anchor link to

모듈 ‘PushwooshFramework’ 빌드 실패

Anchor link to

프로젝트를 빌드할 때 다음과 유사한 오류가 발생할 수 있습니다:

Failed to build module 'PushwooshFramework'; this SDK is not supported by the compiler
(the SDK is built with 'Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)',
while this compiler is 'Apple Swift version 6.1.2 effective-5.10 (swiftlang-6.1.2.1.2 clang-1700.0.13.5)')

원인: 이 오류는 Swift 컴파일러 버전 비호환성과 관련이 없습니다. Pushwoosh iOS SDK 버전 6.8.0부터 SDK는 서로 상호 작용하는 여러 구성 요소로 모듈화되었습니다. 이 오류는 필요한 모든 프레임워크가 프로젝트에 추가되지 않았을 때 발생합니다.

해결 방법: Swift Package Manager를 통해 통합할 때 필요한 네 가지 프레임워크가 모두 앱 타겟에 추가되었는지 확인하십시오:

  • PushwooshFramework
  • PushwooshCore
  • PushwooshBridge
  • PushwooshLiveActivities

Xcode에서 이를 확인하려면:

  1. Project Navigator에서 프로젝트를 선택합니다.
  2. 앱 타겟을 선택합니다.
  3. General > Frameworks, Libraries, and Embedded Content로 이동합니다.
  4. 네 가지 프레임워크가 모두 나열되어 있는지 확인합니다.

통합 과정에서 문제가 발생하면 지원 및 커뮤니티 섹션을 참조하십시오.