이 페이지에서

For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.

iOS SDK 마이그레이션 가이드

Amplitude의 iOS SDK(Amplitude-Swift)의 새 버전은 플러그인 아키텍처, 내장형 타입 정의 및 프런트엔드 프레임워크에 대한 광범위한 지원을 제공합니다. 새 버전은 Amplitude-iOS와 하위 호환되지 않습니다.

Amplitude-Swift로 마이그레이션하려면 종속성 및 계측을 업데이트하십시오.

용어

  • Amplitude-iOS: iOS SDK 유지 관리.
  • Amplitude-Swift: 새로운 iOS SDK.

종속성

Podfile에 AmplitudeSwift 종속성을 추가합니다.

diff
- pod 'Amplitude', '~> 8.14'
+ pod 'AmplitudeSwift', '~> 1.0'

계측 변경 사항

이 SDK는 이벤트를 계측하기 위한 API를 제공합니다. 새로운 SDK로 마이그레이션하려면 몇 가지 호출을 업데이트하십시오. 다음 섹션에서는 변경된 호출에 대해 자세히 설명합니다.

SDK 초기화

Amplitude-Swift는 instance()를 다른 호출과 함께 제거합니다. 새로운 iOS SDK는 객체를 사용하여 구성 값을 Configuration로 설정합니다.

import Amplitude
import AmplitudeSwift
Amplitude.instance().trackingSessionEvents = true
Amplitude.instance().initializeApiKey("YOUR-API-KEY")
let amplitude = Amplitude(configuration: Configuration(
    apiKey: "API_KEY",
    autocapture: [.sessions, .appLifecycles, .screenViews, .networkTracking]
))

SDK 구성

이벤트 추적

유지 관리 iOS SDK는 이벤트 페이로드의 특정 속성을 재정의하기 위해 withEventProperties, withApiProperties, withUserProperties, withGroup, withGroupProperties, withTimestamp 및 outOfSession와 같은 여러 logEvent API를 제공했습니다. Amplitude는 이러한 변형을 하나의 통합 track API로 통합합니다.

logEvent

logEvent() API는 track()에 매핑됩니다.

let eventType = "Button Clicked"
let eventProperties: [String: Any] = ["key": "value"]
Amplitude.instance().logEvent(
 eventType,
 withEventProperties: eventProperties
)
let event = BaseEvent(
  eventType: eventType,
  eventProperties: eventProperties
)
amplitude.track(event: event)

타임스탬프가 있는 로그 이벤트

logEvent() API는 track()에 매핑됩니다.

let eventType = "Button Clicked"
let timestamp = Int64(NSDate().timeIntervalSince1970 * 1000)
Amplitude.instance().logEvent(
 eventType,
 withTimestamp: timestamp
)
let event = BaseEvent(
  eventType: eventType,
  timestamp: timestamp
)
amplitude.track(event: event)

그룹 포함 로그 이벤트

logEvent() API는 track()에 매핑됩니다.

let eventType = "Button Clicked"
let eventProperties: [String: Any] = ["key": "value"]
let groups: [String: Any] = ["orgId": 10]
Amplitude.instance().logEvent(
 eventType,
 withEventProperties: eventProperties,
 withGroups: groups
)
let event = BaseEvent(
  eventType: eventType,
  eventProperties: eventProperties,
  groups: groups
)
amplitude.track(event: event)

업로드 이벤트

uploadEvents() API는 flush()에 매핑됩니다.

Amplitude.instance().uploadEvents()
amplitude.flush()

사용자 속성 설정

사용자 속성을 설정하기 위한 API는 Amplitude-Swift가 instance()를 제거한다는 점을 제외하고 동일합니다. 다음 코드 조각은 사용자 속성 API를 마이그레이션하는 방법을 보여줍니다.

setUserId

ID 길이 제한

유지 관리 SDK는 deviceId및 userId에 대해 길이 제한을 적용하지 않는 오래된 SDK 엔드포인트(api2.amplitude.com)를 사용합니다. 최신 SDK는 Amplitude의 HTTP V2 API(api2.amplitude.com/2/httpapi)를 사용하며 기본적으로 최소 5자의 식별자를 요구합니다. 최신 SDK로 마이그레이션할 때 5자 미만의 식별자를 허용한 경우 config.minIdLength을 더 작은 값으로 설정하십시오.

amplitude에서 getInstance()를 호출하지 않고 사용자 ID를 설정합니다.

let userId = "TEST-USER-ID"
Amplitude.instance().setUserId(userId)
amplitude.setUserId(userId: userId)

setDeviceId

ID 길이 제한

유지 관리 SDK는 deviceId및 userId에 대해 길이 제한을 적용하지 않는 오래된 SDK 엔드포인트(api2.amplitude.com)를 사용합니다. 최신 SDK는 Amplitude의 HTTP V2 API(api2.amplitude.com/2/httpapi)를 사용하며 기본적으로 최소 5자의 식별자를 요구합니다. 최신 SDK로 마이그레이션할 때 5자 미만의 식별자를 허용한 경우 config.minIdLength을 더 작은 값으로 설정하십시오.

amplitude에서 instance()를 호출하지 않고 기기 ID를 설정합니다.

let deviceId = "TEST-DEVICE-ID"
Amplitude.instance().setDeviceId(deviceId)
amplitude.setDeviceId(deviceId: deviceId)

clearUserProperties

Amplitude-Swift는 clearUserPropertiesAPI를 제거하지만 통합 identify API를 사용하여 사용자 속성을 제거할 수 있습니다.

Amplitude.instance().clearUserProperties()
let identify = Identify()
identify.clearAll()
amplitude.identify(identify: identify)

setUserProperties

Amplitude-Swift는 setUserProperties API를 제거하지만 통합 identify API를 사용하여 사용자 속성을 추가할 수 있습니다.

Amplitude.instance().setUserProperties([
  "membership": "paid",
  "payment": "bank",
])
amplitude.identify(userProperties: [
  "membership": "paid",
  "payment": "bank"
])

식별

amplitude에서 instance()를 호출하지 않고 identify 호출을 수행하십시오.

let identify = AMPIdentify()
identify.set("membership", value: "paid")
Amplitude.instance().identify(identify)
let identify = Identify()
identify.set(property: "membership", value: "paid")
amplitude.identify(identify: identify)

그룹 속성 설정

groupIdentify

amplitude에서 instance()를 호출하지 않고 identify 호출을 수행하십시오.

let identify = AMPIdentify()
identify.set("membership", value: "paid")
Amplitude.instance().groupIdentify(
  withGroupType: "TEST-GROUP-TYPE",
  groupName: "TEST-GROUP-NAME",
  groupIdentify: identify
)
let identify = Identify()
identify.set(property: "membership", value: "paid")
amplitude.groupIdentify(
  groupType: "TEST-GROUP-TYPE",
  groupName: "TEST-GROUP-NAME",
  identify: identify
)

매출 추적

logRevenueV2

instance()를 호출하지 않고 amplitude API를 사용하여 revenue()수익을 추적하십시오.

let revenue = AMPRevenue()
revenue.setProductIdentifier("productIdentifier")
revenue.setQuantity(3)
revenue.setPrice(NSNumber(value: 3.99))
Amplitude.instance().logRevenueV2(revenue)
let revenue = Revenue()
revenue.productId = "productIdentifier"
revenue.quantity = 3
revenue.price = 3.99
amplitude.revenue(revenue: revenue)

패턴

플러그인

IDFV 또는 IDFA를 deviceID로 사용할 수 있도록 Amplitude-iOS에서 설정 amplitude.adSupportBlock또는 amplitude.useAdvertisingIdForDeviceId를 사용할 수 있었습니다. Amplitude-Swift는 이러한 구성을 지원하지 않지만 새로운 iOS SDK에 플러그인을 추가하여 이벤트 페이로드를 풍부하게 할 수 있습니다.

import AdSupport
import AmplitudeSwift
import AppTrackingTransparency
import Foundation
import SwiftUI
/// Plugin to collect IDFA values.  Users will be prompted if authorization status is undetermined.
/// Upon completion of user entry a track event is issued showing the choice user made.
///
/// Don't forget to add "NSUserTrackingUsageDescription" with a description to your Info.plist.
class IDFACollectionPlugin: Plugin {
    let type = PluginType.enrichment
    weak var amplitude: Amplitude? = nil
    func execute(event: BaseEvent?) -> BaseEvent? {
        let status = ATTrackingManager.trackingAuthorizationStatus
        var idfa = fallbackValue
        if status == .authorized {
            idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        }
        let workingEvent = event
        // The idfa on simulator is always 00000000-0000-0000-0000-000000000000
        event?.idfa = idfa
        // If you want to use idfa for the device_id
        event?.deviceId = idfa
        return workingEvent
    }
}
extension IDFACollectionPlugin {
    var fallbackValue: String? {
        // fallback to the IDFV value.
        // this is also sent in event.context.device.id,
        // feel free to use a value that is more useful to you.
        return UIDevice.current.identifierForVendor?.uuidString
    }
}
...
// To install your custom plugin, use 'add()' with your custom plugin as parameter.
amplitude.add(plugin: IDFACollectionPlugin())

콜백

Amplitude-Swift 는 성공적인 업로드 및 실패한 업로드에 대해 실행되는 구성 수준 및 이벤트 수준의 콜백 기능을 지원합니다. 구성 수준의 콜백은 성공적이거나 실패한 모든 이벤트 업로드에 대해 실행됩니다. 이벤트 수준 콜백은 특정 이벤트에 대해서만 실행됩니다. Amplitude-Swift는 이벤트 수준의 콜백을 캐시에 저장하므로 앱이 충돌할 경우 SDK에서 이러한 콜백이 손실됩니다.

let amplitude = Amplitude(
    configuration: Configuration(
        apiKey: "TEST-API-KEY",
        callback: { (event: BaseEvent, code: Int, message: String) -> Void in
            print("eventCallback: \(event), code: \(code), message: \(message)")
        },
    )
)

이벤트 수준 콜백:

swift
let event = BaseEvent(
    callback: { (event: BaseEvent, code: Int, message: String) -> Void in
        print("eventCallback: \(event), code: \(code), message: \(message)")
    },
    eventType: "TEST-EVENT-TYPE")
amplitude.track(event: event)

또는:

swift
let event2 = BaseEvent(eventType:"test")
amplitude.track(
    event: event2,
    callback: { (event: BaseEvent, code: Int, message: String) -> Void in
        print("eventCallback: \(event), code: \(code), message: \(message)")
})

데이터 마이그레이션

기본적으로 Amplitude-Swift는 기존 유지 관리 SDK 데이터(이벤트, 사용자/장치 ID)를 최신 SDK로 이동합니다. 데이터 마이그레이션을 비활성화하려면 구성에서 migrateLegacyData을 false로 설정하십시오.

macOS 앱이 샌드박스화되어 있지 않은 경우 기존 SDK의 데이터는 마이그레이션되지 않습니다. 샌드박싱에 대한 자세한 내용과 앱이 샌드박스화되어 있는지 확인하는 방법은 Apple의 기사 앱 샌드박스로 사용자 데이터 보호를 참조하십시오.

amplitude = Amplitude(
    configuration: Configuration(
        ...
        migrateLegacyData: false,
    )
)

이 내용이 도움이 되었나요?