iOS 푸시 알림은 iOS 앱에서 지속적인 사용자 참여와 유지율을 높이는 데 필수적입니다. 실시간 업데이트, 리마인더 및 개인화된 메시지를 사용자에게 직접 전달하여 앱의 전반적인 사용자 경험과 고착도를 향상시킬 수 있습니다. OneSignal의 SDK를 앱과 통합하면 Apple Push Notification Service(APNS)를 활용하여 iOS 기기 전반에 걸쳐 알림이 원활하게 전달되도록 할 수 있습니다. 이 가이드는 iOS 앱에 SDK를 통합하는 과정을 안내합니다.
사용자 정의 App Group 이름을 사용하고 group.your_bundle_id.onesignal이 아닌 경우 App Target 및 OneSignalNotificationServiceExtension Target의 Info.plist 둘 다에 App Group ID를 추가해야 합니다! 자세한 내용은 3단계를 참조하세요.
NotificationService.swift 또는 NotificationService.m 파일의 내용을 다음으로 바꾸세요:
import UserNotificationsimport OneSignalExtensionclass NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var receivedRequest: UNNotificationRequest! var bestAttemptContent: UNMutableNotificationContent? // Note this extension only runs when `mutable_content` is set // Setting an attachment or action buttons automatically sets the property to true override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.receivedRequest = request self.contentHandler = contentHandler self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { // DEBUGGING: Uncomment the 2 lines below to check this extension is executing// print("Running NotificationServiceExtension")// bestAttemptContent.body = "[Modified] " + bestAttemptContent.body OneSignalExtension.didReceiveNotificationExtensionRequest(self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler) } } override func serviceExtensionTimeWillExpire() { // 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 { OneSignalExtension.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent) contentHandler(bestAttemptContent) } }}
#import <OneSignalExtension/OneSignalExtension.h>#import "NotificationService.h"@interface NotificationService ()@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);@property (nonatomic, strong) UNNotificationRequest *receivedRequest;@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;@end@implementation NotificationService// Note, this extension only runs when mutable-content is set// Setting an attachment or action buttons automatically adds this- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler { self.receivedRequest = request; self.contentHandler = contentHandler; self.bestAttemptContent = [request.content mutableCopy]; // DEBUGGING: Uncomment the 2 lines below and comment out the one above to ensure this extension is executing// NSLog(@"Running NotificationServiceExtension");// self.bestAttemptContent.body = [@"[Modified] " stringByAppendingString:self.bestAttemptContent.body]; [OneSignalExtension didReceiveNotificationExtensionRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent withContentHandler:self.contentHandler];}- (void)serviceExtensionTimeWillExpire { // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. [OneSignalExtension serviceExtensionTimeWillExpireRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent]; self.contentHandler(self.bestAttemptContent);}@end
OneSignal 패키지가 설치되지 않아 오류가 표시됩니다. 이는 다음 단계에서 해결됩니다.
Xcode Package Dependencies Manager (Swift Package Manager) 또는 CocoaPods를 사용하여 SDK를 추가하세요. 4개의 사용 가능한 라이브러리가 있습니다. 인앱 메시지 및/또는 위치 추적을 원하지 않는 경우 이러한 패키지를 생략할 수 있습니다.
라이브러리
타겟
필수 여부
OneSignalExtension
OneSignalNotificationServiceExtension
✅
OneSignalFramework
App
✅
OneSignalInAppMessages
App
권장
OneSignalLocation
App
선택 사항
Xcode Package Dependencies
CocoaPods
**File > Add Package Dependencies…**로 이동하여 OneSignal SDK 저장소의 URL을 입력하세요:https://github.com/OneSignal/OneSignal-XCFrameworkonesignal-xcframework 패키지를 선택하고 Add Package를 클릭하세요.OneSignal-XCFramework에 대한 패키지 제품을 선택하세요.
요구 사항: CocoaPods 1.16.2+ (설정 지침은 CocoaPods 1.16.2 사용).Podfile을 열고 다음을 추가하세요:
Podfile
# If platform is uncommented, set to the same value as your minimum deployment target in Xcode # platform :ios, '15.0' target 'your_project_name' do pod 'OneSignal/OneSignal', '>= 5.2.9', '< 6.0' # If your app does not use In-App messages, you can remove this: pod 'OneSignal/OneSignalInAppMessages', '>= 5.2.9', '< 6.0' # If your app does not use CoreLocation, you can remove this: pod 'OneSignal/OneSignalLocation', '>= 5.2.9', '< 6.0' # Your other pods here end target 'OneSignalNotificationServiceExtension' do pod 'OneSignal/OneSignal', '>= 5.2.9', '< 6.0' end
종속성을 메인 앱 타겟과 OneSignalNotificationServiceExtension 타겟에 추가하세요. platform이 주석 처리되지 않은 경우 Xcode의 최소 배포 타겟과 동일한 값인지 확인하세요.다음 명령을 실행하여 OneSignal iOS SDK pod를 가져와 프로젝트에 추가하세요:pod repo update && pod install설치가 완료되면 프로젝트 이름을 딴 XCWorkspace 파일(예: <project-name>.xcworkspace)을 열어야 합니다.
OneSignal iOS SDK pod를 사용할 때는 프로젝트를 열기 위해 반드시 .xcworkspace 파일을 사용해야 합니다.
다음 오류가 발생할 수 있으며, 다음과 같이 해결할 수 있습니다.
ArgumentError - \[Xcodeproj] Unable to find compatibility version string for
object version `70`.
CocoaPods는 xcodeproj Ruby gem에 의존하여 Xcode 프로젝트 파일을 읽습니다. 현재 최신 xcodeproj 릴리스는 Xcode 16에서 도입된 object version 70을 인식하지 못합니다. 따라서 CocoaPods가 .xcodeproj 파일을 열려고 하면 이 오류와 함께 충돌합니다.
Xcode를 닫으세요.
프로젝트의 ios/<your-app>.xcodeproj/project.pbxproj 파일로 이동하세요.
SwiftUI 인터페이스를 사용하는 경우 <APP_NAME>App.swift 파일로 이동하여 제공된 메서드로 OneSignal을 초기화하세요.OneSignal 대시보드 **Settings > Keys & IDs**에서 찾은 OneSignal 앱 ID로 YOUR_APP_ID를 바꾸세요. OneSignal 앱에 액세스할 수 없는 경우 팀 멤버에게 초대를 요청하세요.
import SwiftUIimport OneSignalFramework@mainstruct YOURAPP_NAME: App { //Connect the SwiftUI app to the UIKit app delegate @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } }}class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { // Enable verbose logging for debugging (remove in production) OneSignal.Debug.setLogLevel(.LL_VERBOSE) // Initialize with your OneSignal App ID OneSignal.initialize("YOUR_APP_ID", withLaunchOptions: launchOptions) // Use this method to prompt for push notifications. // We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission. OneSignal.Notifications.requestPermission({ accepted in print("User accepted notifications: \(accepted)") }, fallbackToSettings: false) return true }}
Storyboard 인터페이스를 사용하는 경우 AppDelegate 파일로 이동하여 제공된 메서드로 OneSignal을 초기화하세요.OneSignal 대시보드 **Settings > Keys & IDs**에서 찾은 OneSignal 앱 ID로 YOUR_APP_ID를 바꾸세요. OneSignal 앱에 액세스할 수 없는 경우 팀 멤버에게 초대를 요청하세요.
//AppDelegate.swiftimport UIKitimport OneSignalFramework@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate {func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Enable verbose logging for debugging (remove in production) OneSignal.Debug.setLogLevel(.LL_VERBOSE) // Initialize with your OneSignal App ID OneSignal.initialize("YOUR_APP_ID", withLaunchOptions: launchOptions) // Use this method to prompt for push notifications. // We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission. OneSignal.Notifications.requestPermission({ accepted in print("User accepted notifications: \(accepted)") }, fallbackToSettings: false) return true}// Remaining contents of your AppDelegate Class...}
#import <OneSignalFramework/OneSignalFramework.h>@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Enable verbose logging for debugging (remove in production) [OneSignal.Debug setLogLevel:ONE_S_LL_VERBOSE]; // Initialize with your OneSignal App ID [OneSignal initialize:@"YOUR_APP_ID" withLaunchOptions:launchOptions]; // Use this method to prompt for push notifications. // We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission. [OneSignal.Notifications requestPermission:^(BOOL accepted) { NSLog(@"User accepted notifications: %d", accepted); } fallbackToSettings:false]; // Login your customer with externalId // [OneSignal login:@"EXTERNAL_ID"]; return YES;}
이전에는 모바일 구독을 생성하는 방법을 시연했습니다. 이제 OneSignal SDK를 사용하여 모든 구독(푸시, 이메일 및 SMS 포함)에서 사용자를 식별하는 것으로 확장하겠습니다. 플랫폼 전반에 걸쳐 사용자를 통합하고 참여시키는 데 도움이 되는 External ID, 태그, 다중 채널 구독, 개인 정보 보호 및 이벤트 추적을 다룹니다.
External ID를 사용하여 백엔드의 사용자 식별자를 사용하여 기기, 이메일 주소 및 전화번호 전반에 걸쳐 사용자를 일관되게 식별하세요. 이렇게 하면 채널 및 타사 시스템 전반에 걸쳐 메시징이 통합된 상태로 유지됩니다(통합에 특히 중요).앱에서 식별될 때마다 SDK의 login 메서드로 External ID를 설정하세요.
OneSignal은 구독(Subscription ID) 및 사용자(OneSignal ID)에 대한 고유한 읽기 전용 ID를 생성합니다.사용자가 다른 기기에 앱을 다운로드하거나, 웹사이트를 구독하거나, 앱 외부에서 이메일 주소 및 전화번호를 제공하면 새 구독이 생성됩니다.SDK를 통해 External ID를 설정하는 것은 생성 방법에 관계없이 모든 구독에서 사용자를 식별하는 데 매우 권장됩니다.
태그는 사용자 속성(username, role 또는 기본 설정 등) 및 이벤트(purchase_date, game_level 또는 사용자 상호 작용 등)를 저장하는 데 사용할 수 있는 문자열 데이터의 키-값 쌍입니다. 태그는 고급 메시지 개인화 및 세그먼테이션을 지원하여 보다 고급 사용 사례를 가능하게 합니다.앱에서 이벤트가 발생할 때 SDK addTag 및 addTags 메서드로 태그를 설정하세요.이 예시에서 사용자는 current_level이라는 태그가 6의 값으로 설정되어 식별 가능한 레벨 6에 도달했습니다.
레벨이 5에서 10 사이인 사용자 세그먼트를 생성하고 이를 사용하여 타겟팅되고 개인화된 메시지를 보낼 수 있습니다:
기본적으로 OneSignal SDK는 메서드 스위즐링을 사용하여 푸시 알림 델리게이트 메서드를 자동으로 처리합니다. 앱에서 스위즐링을 비활성화해야 하는 경우(예: 다른 SDK와의 충돌을 방지하거나 알림 델리게이트 메서드에 대한 완전한 제어를 유지하기 위해) Info.plist를 통해 이를 해제할 수 있습니다.스위즐링이 비활성화된 경우 알림 델리게이트 메서드를 OneSignal SDK에 수동으로 전달해야 합니다. 다른 모든 SDK 기능(리스너, 옵저버, 인앱 메시지, 아웃컴 등)은 계속 정상적으로 작동합니다.