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。
依存関係
AmplitudeSwift依存関係をPodfileに追加します。
- 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 を設定する
| Amplitude-iOS | Amplitude-Swift |
|---|---|
amplitude.instanceWithName("YOUR-INSTANCE-NAME") | config.instanceName |
amplitude.useDynamicConfig | サポートされていません。 |
amplitude.setServerUrl("YOUR-SERVER-URL") | config.serverUrl |
amplitude.setServerZone("AMPServerZone.EU or AMPServerZone.US") | config.serverZone |
amplitude.trackingOptions | config.trackingOptions |
amplitude.trackingSessionEvents | config.autocapture.sessions |
amplitude.minTimeBetweenSessionsMillis | config.minTimeBetweenSessionsMillis |
amplitude.eventUploadMaxBatchSize | config.flushQueueSize |
amplitude.eventUploadThreshold | config.flushQueueSize |
amplitude.eventUploadPeriodSeconds | config.flushIntervalMillis |
| 最大再試行回数を設定します。サポートされていません。 | config.flushMaxRetries |
amplitude.eventMaxCount | サポートされていません。 |
amplitude.optOut | config.optOut |
amplitude.enableCoppaControl() or amplitude.disableCoppaControl() | config.enableCoppaControl |
| ストレージプロバイダをカスタマイズします。 サポートされていません。 | config.storageProvider |
| ログレベルを設定します。サポートされていません。 | config.logLevel |
| ロガープロバイダーをカスタマイズします。 サポートされていません。 | config.loggerProvider |
deviceIdおよびuserIdに最小長はありません。 | 最小長は5です。config.minIdLengthはdeviceIdおよびuserIdの最小長を上書きします。 |
| パートナー統合用のパートナー ID。 サポートされていません。 | config.partnerId |
| イベントのコールバック。 サポートされていません。 ミドルウェアを参照してください。 | config.callback |
amplitude.libraryName | サポートされていません。 |
amplitude.libraryVersion | サポートされていません。 |
amplitude.adSupportBlock | サポートされていません。 プラグインを参照。 |
amplitude.useAdvertisingIdForDeviceId | サポートされていません。 プラグインを参照。 |
amplitude.locationInfoBlock | サポートされていません。 プラグインを参照。 |
amplitude.deferCheckInForeground | サポートされていません。 |
amplitude.setOffline(Yes) | サポートされていません。 |
amplitude.setContentTypeHeader("YOUR-CONTENT-TYPE-HEADER") | サポートされていません。 |
amplitude.setPlan(plan) | config.plan |
plan.setBranch("YOUR-BRANCH") | config.plan.branch |
plan.setSource("YOUR-SOURCE") | config.plan.source |
plan.setVersion("YOUR-VERSION") | config.plan.version |
plan.setVersionId("YOUR-VERSION-ID") | config.plan.versionId |
amplitude.setTrackingOptions(options) | config.trackingOptions |
amplitude.setSessionId(timestamp) | amplitude.setSessionId(timestamp:) |
イベントを追跡
メンテナンスiOS SDKでは、イベントペイロード内の特定のプロパティを上書きするために、withEventProperties、withApiProperties、withUserProperties、withGroup、withGroupProperties、withTimestamp、およびoutOfSessionを使用する複数のlogEventAPIを提供していました。Amplitudeはこれらのバリエーションを1つのtrackAPIに統合しています。
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 withTimestamp
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)
withGroupを使用したlogEvent
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
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をより小さい値に設定してください。
getInstance()を呼び出さずにamplitudeのユーザー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をより小さい値に設定してください。
instance()を呼び出さずに、amplitudeのデバイスIDを設定します。
let deviceId = "TEST-DEVICE-ID"
Amplitude.instance().setDeviceId(deviceId)
amplitude.setDeviceId(deviceId: deviceId)
clearUserProperties
Amplitude-SwiftではclearUserPropertiesAPIが削除されましたが、統合identifyAPIを使用してユーザープロパティを削除することができます。
Amplitude.instance().clearUserProperties()
let identify = Identify()
identify.clearAll()
amplitude.identify(identify: identify)
setUserProperties
Amplitude-SwiftではsetUserPropertiesAPIが削除されましたが、統合identifyAPIを使用してユーザープロパティを追加することができます。
Amplitude.instance().setUserProperties([
"membership": "paid",
"payment": "bank",
])
amplitude.identify(userProperties: [
"membership": "paid",
"payment": "bank"
])
identify
instance()を呼び出さずにamplitudeで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
instance()を呼び出さずにamplitudeで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でrevenue()APIを使用して収益を追跡します。
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)
パターン
プラグイン
Amplitude-iOSでは、configs amplitude.adSupportBlockまたはamplitude.useAdvertisingIdForDeviceIdを使用して、IDFVまたはIDFAをdeviceIDとして使用できました。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)")
},
)
)
イベントレベルのコールバック:
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)
または:
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の記事「App Sandboxでユーザーデータを保護する」を参照してください。
amplitude = Amplitude(
configuration: Configuration(
...
migrateLegacyData: false,
)
)
Was this helpful?