メインコンテンツまでスキップ

iOS SDK+ 統合ガイド

Language

このページでは、Rokt Ecommerce iOS SDK+の実装方法について説明します。SDK+は、設定された画面でユーザーとトランザクションデータをRoktに渡し、Roktが確認画面でのオファーなどの関連するエクスペリエンスを表示できるようにします。

1. Add the Rokt SDK+ to Your iOS App#

Rokt SDK+は、最低でもiOS 15.0のデプロイメントターゲットが必要です。プロジェクトで既に使用しているSwift Package ManagerまたはCocoaPodsを使用してください。

1Add the Rokt SDK+ to your iOS app#

Install method

Xcodeで、File → Add Package Dependenciesを選択し、https://github.com/ROKT/rokt-sdk-plus-ios.gitを入力し、依存関係ルールをUp to Next Major Versionに設定し、**RoktSDKPlus**製品をアプリターゲットに追加します。または、Package.swiftで固定します:

PackageRepository URLProduct
Rokt SDK+ for iOShttps://github.com/ROKT/rokt-sdk-plus-ios.gitRoktSDKPlus
Package.swift
dependencies: [
.package(url: "https://github.com/ROKT/rokt-sdk-plus-ios.git", from: "9.2.0"),
]

2. Initialize the Rokt SDK+#

AppDelegateファイルに次の初期化スニペットを挿入します。your-keyyour-secretをRoktチームから提供されたキーとシークレットに置き換えてください。

AppDelegate initialization
import mParticle_Apple_SDK
import RoktPaymentExtension

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Initialize the SDK+
let options = MParticleOptions(key: "your-key",
secret: "your-secret")
// Specify the data environment with environment:
// Set it to .development if you are still testing your integration.
// Set it to .production if your integration is ready for production data.
// The default is .autoDetect which attempts to detect the environment automatically
options.environment = .development

// Enter your custom subdomain if you are using a first-party domain configuration (optional)
let networkOptions = MPNetworkOptions()
networkOptions.customBaseURL = URL(string: "https://rkt.example.com")
options.networkOptions = networkOptions

// Identify the current user:
let identifyRequest = MPIdentityApiRequest.withEmptyUser()

// If you're using an un-hashed email address, set it in 'email'.
identifyRequest.email = "j.smith@example.com"

// If you're using a hashed email address, set it in 'other' instead of email
identifyRequest.setIdentity("sha256 hashed email goes here", identityType: .other)
// Customer phone number in E.164 format.
identifyRequest.setIdentity("+13125551515", identityType: .phoneNumber)
// If you can only provide a SHA-256-hashed mobile number, set it in 'other4' instead of 'phoneNumber' — do not pass both.
identifyRequest.setIdentity("sha256 hashed mobile goes here", identityType: .other2)

// If the user is identified with their email address, set additional user attributes.
options.identifyRequest = identifyRequest
options.onIdentifyComplete = {(result: MPIdentityApiResult?, error: Error?) in
if let user = result?.user {
user.setUserAttribute("example attribute key", value: "example attribute value")
}
}
MParticle.sharedInstance().start(with: options)

// Register after mParticle.start(), before selectShoppableAds
if let paymentExt = RoktPaymentExtension(
applePayMerchantId: "merchant.com.yourapp.rokt", // omit if not offering Apple Pay
urlScheme: "myapp" // omit if not offering Afterpay / Clearpay
) {
MParticle.sharedInstance().rokt.registerPaymentExtension(paymentExt)
}
return true
}
注記

mParticle Rokt kit設定(mParticleダッシュボード)でstripePublishableKeyを設定します。このキットは登録時にstripeKeyとしてRoktに転送します—コード内で渡す必要はありません。アプリ内では、Apple PayのマーチャントIDおよび/またはurlSchemeRoktPaymentExtension作成時に提供します。applePayMerchantIdまたはurlSchemeの少なくとも一つを提供する必要があります。両方が省略されると、初期化子はnilを返します。

AppDelegateに初期化スニペットを挿入すると、次のカスタマイズ可能なフィールドが表示されます:

1Entering your Rokt key and secret#

keysecretをRoktアカウントマネージャーから提供された値に設定します。

2Setting your data environment#

environmentをテスト中は.development(Swift)またはMPEnvironmentDevelopment(Objective-C)に設定してデータを開発環境にルーティングし、実際の顧客活動をProductionに送信するには.productionまたはMPEnvironmentProductionに設定します。

3Entering a custom first-party domain#

First-Party Domain Configurationの指示に従い、customBaseURLMPNetworkOptionsに設定してカスタムサブドメインを使用します。Rokt SDK+を独自のドメイン経由でルーティングすることで、広告ブロッカーやブラウザが広告やデータをブロックするリスクを減らします。options.networkOptionsを省略すると、Roktのデフォルトエンドポイントにトラフィックを送信します。

4Identifying your user and setting attributes#

identifyRequestで、ユーザーの生のハッシュされていないメールをemailプロパティに渡します。ハッシュされたメールやその他の識別子については、Supported User Identifiersを参照してください。識別が完了したら、onIdentifyCompleteコールバックを使用して追加のユーザー属性を設定します—推奨リストについてはUser Attributesを参照してください。

onIdentifyComplete
options.onIdentifyComplete = {(result: MPIdentityApiResult?, error: Error?) in
if let user = result?.user {
user.setUserAttribute("example attribute key", value: "example attribute value")
}
}
注記

初期化スニペットには必ずidentifyRequestを含めてください。初期化時にユーザーのメールアドレスがない場合は、割り当てを省略しても構いません。SDK+は初期化され、後で3. ユーザーの識別を通じてユーザーを識別できます。エラーハンドリングを参照して、error引数を検査する方法を確認してください。エラーハンドリングがないと、大規模なデータ整合性の問題が発生する可能性があります。

5Registering the payment extension#

RoktPaymentExtensionMParticle.sharedInstance().start()の後、selectShoppableAdsの前に登録して、Shoppable Adsの支払いを有効にします。すべてのShoppable Ads配置には登録が必要です。Apple PayにはapplePayMerchantIdを、Afterpay / ClearpayにはurlSchemeを渡すか、両方を渡してください。付録E: Shoppable Ads支払いの設定を参照してください。拡張機能はSwiftで作成および登録されます。Objective-Cアプリでは、小さなSwiftファイルからこれを行ってください。

3. Identify the User#

SDK+初期化スクリプトは、スクリプトのidentifyRequestオブジェクトに提供された識別子を使用して現在のユーザーを識別します。SDKの初期化後、ユーザーがログイン、ログアウト、またはチェックアウト時などに識別子を提供するたびに、適切な方法を使用してユーザーのアイデンティティを同期させる必要があります。

サポートされているユーザー識別子サポートされているユーザー識別子 への直接リンク

サポートされているユーザー識別子を表示
フィールドタイプ説明
emailstring顧客の生のハッシュ化されていないメールアドレスを identifyRequest.email に割り当てます。
emailSha256stringSHA-256 ハッシュ化されたメール(iOS パス)。identifyRequest.setIdentity(hashedEmail, identityType: .other) を介して渡します。ハッシュ化された形式のみが利用可能な場合は、email の代わりに使用します。
mobileSha256stringSHA-256 ハッシュ化された携帯番号(iOS パス)。identifyRequest.setIdentity(hashedMobile, identityType: .other4) を介して渡します。
mobilestringE.164 形式の電話番号。identifyRequest.setIdentity(mobileNumber, identityType: .phoneNumber) を介して渡します。
customeridstring内部の顧客/アカウント識別子を identifyRequest.customerId に割り当てます。

ユーザーを識別するには:

1Create an identifyRequest object#

ユーザーの識別子を含む identifyRequest オブジェクトを作成します。

2Create an identityCallback#

識別が成功した後に追加のユーザー属性を設定するための identityCallback を作成します。

3Send the request using the method that matches the user's action#

ユーザーのアクションに一致するメソッドに identifyRequest (およびオプションの identityCallback)を渡します:

  • MParticle.sharedInstance().identity.login: ユーザーがログインまたはアカウントを作成したときに呼び出します。
  • MParticle.sharedInstance().identity.identify: ログインの遷移なしでセッション中にユーザーのメールを取得したときに呼び出します(例:ゲストがチェックアウト時にメールを入力する場合)。
  • MParticle.sharedInstance().identity.logout: ユーザーがログアウトしたときに呼び出します。

これらのメソッドを呼び出すことで、SDK の現在のユーザー状態の記録が遷移します。loginlogout メソッドは、Rokt の帰属を改善するために対応するイベントも自動的にログします。

例えば、メール j.smith@example.com、携帯番号 +13125551515、顧客 ID cust_10482 を持つユーザー Jane Smith の場合:

Identify Jane Smith
// 1. Create the identifyRequest object
let identifyRequest = MPIdentityApiRequest.withEmptyUser()
identifyRequest.email = "j.smith@example.com"
// Customer phone number in E.164 format.
identifyRequest.setIdentity("+13125551515", identityType: .phoneNumber)
// If you can only provide a SHA-256-hashed mobile number, use .other2 instead of .phoneNumber — do not pass both.
identifyRequest.setIdentity("SHA-256 hashed mobile number", identityType: .other2)

// 2. User attributes are set using identityCallback
let identityCallback = {(result: MPIdentityApiResult?) in
if let user = result?.user {
user.setUserAttribute("firstname", value: "Jane")
user.setUserAttribute("lastname", value: "Smith")
}
}

// 3. Call one of the following methods that best matches the user's action:
MParticle.sharedInstance().identity.login(identifyRequest, completion: identityCallback) // Call when the user logs in or creates an account
MParticle.sharedInstance().identity.identify(identifyRequest, completion: identityCallback) // Call when you obtain the user's email mid-session, but not during a login
MParticle.sharedInstance().identity.logout() // Call when the user logs out

4. Set User Attributes#

ユーザーがアプリをナビゲートする際に、段階的に ユーザー属性を設定してください。チェックアウト時だけでなく、設定する属性が多いほど、Rokt は顧客をより正確に解決し、関連するオファーを提供できます。

Set User Attributes
import mParticle_Apple_SDK

// Retrieve the current user. This will only succeed if you have identified the user during SDK+ initialization or by calling the identify method.
let currentUser = MParticle.sharedInstance().identity.currentUser

// Once you have successfully set the current user to `currentUser`, you can set user attributes with:
currentUser?.setUserAttribute("custom-attribute-name", value: "custom-attribute-value")
// Note: all user attributes (including list attributes and tags) must have distinct names.

// Rokt recommends setting as many of the following user attributes as possible:
currentUser?.setUserAttribute("firstname", value: "John")
currentUser?.setUserAttribute("lastname", value: "Doe")
// Phone numbers can be formatted either as '1234567890', or '+1 (234) 567-8901'
currentUser?.setUserAttribute("mobile", value: "3125551515")
currentUser?.setUserAttribute("age", value: "33")
currentUser?.setUserAttribute("gender", value: "M")
currentUser?.setUserAttribute("billingcity", value: "Brooklyn")
currentUser?.setUserAttribute("billingstate", value: "NY")
currentUser?.setUserAttribute("billingzipcode", value: "123456")
currentUser?.setUserAttribute("dob", value: "yyyymmdd")
currentUser?.setUserAttribute("title", value: "Mr")
currentUser?.setUserAttribute("language", value: "en")
currentUser?.setUserAttribute("predictedltv", value: "136.23")

// You can create a user attribute to contain a list of values
currentUser?.setUserAttributeList("favorite-genres", values: ["documentary", "comedy", "romance", "drama"])

// To remove a user attribute, call removeUserAttribute and pass in the attribute name. All user attributes share the same key space.
currentUser?.removeUserAttribute("attribute-to-remove")

ユーザー属性ユーザー属性 への直接リンク

収集可能な限り、以下の項目を設定してください:

すべてのユーザー属性を表示
フィールドタイプ説明
firstnamestring顧客の名。パーソナライズに使用されます。
lastnamestring顧客の姓。パーソナライズに使用されます。
mobilestring電話番号は 1112345678 または +1 (222) 345-6789 の形式で記載。アイデンティティ解決と関連性に使用されます。
birthyearinteger顧客の生年 (例: 1990)。生年月日フィールドとして推奨。代替: dob, age。適格性と関連性に使用されます。
ageinteger顧客の年齢。dob の代替。適格性と関連性に使用されます。
dobstring生年月日、yyyymmddage の代替。適格性と関連性に使用されます。
genderstring顧客の性別。例: M, F, Male, または Female。関連性に使用されます。
titlestring敬称。例: Mr, Mrs, Ms。パーソナライズに使用されます。
languagestring購入に関連付けられたISO 639-1言語コード。関連性に使用されます。
billingaddress1string住所 (例: 123 Main St)。アイデンティティ解決と関連性に使用されます。
billingaddress2stringアパート/ユニット (例: Apt 4B)。アイデンティティ解決に使用されます。
billingcitystring請求先の市。関連性に使用されます。
billingstatestring請求先の州/県/地域。関連性と適格性に使用されます。
billingzipcodestring完全なZIPまたは郵便番号 (米国の優先形式はZIP+4)。アイデンティティ解決と関連性に使用されます。
countrystringISO 3166-1 alpha-2国コード (例: US, GB, AU)。適格性と関連性に使用されます。
newcustomerboolean初めての購入者かどうか。関連性に使用されます。
customertypestringユーザーが認証されているかどうか (guest / logged_in)。関連性に使用されます。
loyaltytierstringパートナーのロイヤルティプログラムの階層。関連性と適格性に使用されます。
loyaltyidstringロイヤルティプログラムのメンバーID。アイデンティティ解決に使用されます。
predictedltvdecimal予測される総生涯価値。通常はパートナーの機械学習モデルから得られます。関連性に使用されます。
subscriptionstatusstring該当する場合のサブスクリプション状態 (active, trial, churned, paused, none)。関連性と適格性に使用されます。
customersegmentstringパートナー内部のセグメンテーション (例: vip, at_risk, new, reactivated)。関連性に使用されます。
acquisitionchannelstring顧客が最初に獲得された方法。関連性に使用されます。

すべてのユーザー属性(リスト属性を含む)は、異なる名前を持たなければなりません。

5. Log Events#

画面ビュー、コマースイベント、およびカスタムイベントを追跡して、Roktが各顧客がどの段階にいるかを理解できるようにします。

Event category

logScreen を画面の名前(例: "homepage", "product_detail_page")と共に呼び出します。追加のカスタム属性を eventInfo に含めます。

Log a screen view
MParticle.sharedInstance().logScreen(
"homepage",
eventInfo: ["custom-attribute": "custom-value"]
)

6. Show a Placement#

Roktがコンテンツを表示するために、すべての支払いおよび確認画面でselectPlacementsを呼び出します。画面の種類とテストまたは本番環境であるかを指定するために、以下のページ識別子のいずれかを含めます。

  • stg.rokt.conf: A confirmation screen in a staging (or testing) environment.
  • prod.rokt.conf: A confirmation screen in a production environment.
  • stg.rokt.payments: A payments screen in a staging (or testing) environment.
  • prod.rokt.payments: A payments screen in a production environment.

画面が読み込まれ、すべての関連属性が利用可能になったらすぐに、selectPlacementsを呼び出します。最低限、emailfirstnamelastnamebillingzipcode、およびconfirmationrefを渡します。完全なリストはPlacement Attributesを参照してください。

Pay+

Pay+プレースメントの場合、各ページでのselectPlacements呼び出しにpaymenttypepaymentServiceProviderを含めます。paymentServiceProviderは支払いページで利用可能な支払い方法を伝え、paymenttypeはユーザーが支払った方法を伝えます。

Placement position
Overlay placement
import mParticle_Apple_SDK
let attributes = [
"email": "test@gmail.com",
"firstname": "Jenny",
"lastname": "Smith",
"billingzipcode": "07762",
"confirmationref": "54321"
]

MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes)

追加設定追加設定 への直接リンク

配置UIをカスタマイズするために、RoktConfigのようなオプションのパラメータを渡します(例: ダーク/ライトモード)。埋め込みビューやonEventコールバックを含む追加のオプションパラメータが以下に示されています。

selectPlacements with RoktConfig
let roktConfig = RoktConfig.Builder().colorMode(.light).build()

MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes, embeddedViews: nil, config: roktConfig) { _ in }
注記

異なる値でRoktExperienceまたは埋め込み識別子RoktEmbedded1を更新したい場合は、Roktアカウントマネージャーに連絡して、Rokt配置が一貫して設定されていることを確認してください。

オプション機能オプション機能 への直接リンク

機能目的
Rokt.close()オーバーレイ配置を自動的に閉じる。
注記

サポートされている属性の完全なリストについては、以下のPlacement Attributesを参照してください。

Roktチームがブランドに合わせて配置レイアウトを設定します。

配置属性配置属性 への直接リンク

これらの属性をattributes辞書にselectPlacementsとして渡します。常に最新の値を提供してください。ここで渡された属性は、以前のsetUserAttribute呼び出しを上書きします。

すべての配置属性を表示
フィールドタイプ説明
emailstring顧客のメールアドレス(ハッシュされていない)。アイデンティティ解決とShoppable Adsの注文確認に使用されます。
firstnamestring顧客の名前。パーソナライゼーションとShoppable Adsの注文履行に使用されます。
lastnamestring顧客の姓。パーソナライゼーションとShoppable Adsの注文履行に使用されます。
mobilestringE.164形式の顧客の携帯電話番号。アイデンティティ解決に使用されます。
confirmationrefstring注文/確認参照番号。関連性、重複排除、Shoppable Adsの注文調整に使用されます。
currencystring取引通貨(ISO 4217、例: USD, GBP, AUD)。関連性とShoppable Adsに使用されます。
countrystringISO 3166-1 alpha-2の国コード。適格性と関連性に使用されます。
languagestring顧客の希望言語(ISO 639-1)。関連性に使用されます。
totalpricedecimal税金と送料を含むカートの合計値。関連性に使用されます。
amountdecimal税金と送料を含まないカートの小計。totalpriceとは異なります。関連性とShoppable Adsに使用されます。
cartItemsarrayカートラインオブジェクトの構造化された配列。キャメルケースである必要があります。関連性に使用されます。
couponcodestring適用されたプロモーションコード(ある場合)。関連性に使用されます。
newcustomerboolean初回購入者かどうか。関連性に使用されます。
customertypestringguestまたはlogged_in。関連性に使用されます。
valuedecimal顧客の累積購入価値。関連性に使用されます。
subscriptionstatusstring該当する場合のサブスクリプション状態(active, trial, churned, paused, none)。関連性と適格性に使用されます。
customersegmentstringパートナー内部セグメンテーション(vip, at_risk, new, reactivated)。関連性に使用されます。
paymenttypestring選択された支払い方法 (credit_card, paypal, apple_pay など)。Pay+ の適格性および Shoppable Ads の支払い方法の優先順位付けに使用されます。
paymentServiceProviderstringページで受け入れられる支払い方法のカンマ区切りリスト(例: applepay,paypal,cardpayment)。値は小文字でスペースを含まない必要があります。受け入れられる値の完全なリストについては、Payment Service Provider を参照してください。Pay+ の適格性に使用されます。
ccbinstringクレジットカードの BIN(6-8 桁)。関連性に使用されます。
billingaddress1string請求先の住所。アイデンティティ解決と関連性に使用されます。
billingaddress2string請求先のアパート/ユニット。アイデンティティ解決に使用されます。
billingcitystring請求先の市区町村。関連性に使用されます。
billingstatestring請求先の州または省。関連性に使用されます。
billingzipcodestring請求先の郵便番号/郵便番号。アイデンティティ解決と関連性に使用されます。
billingnamestring請求先住所のカード所有者のフルネーム。アイデンティティ解決に使用されます。
shippingmethodstring選択された配送方法 (standard, express, next_day)。関連性に使用されます。
shippingnamestring配送先住所の受取人のフルネーム。Shoppable Ads の注文履行に使用されます。
shippingaddress1string配送先の住所。関連性と Shoppable Ads の注文履行に使用されます。
shippingcitystring配送先の市区町村。関連性と Shoppable Ads の注文履行に使用されます。
shippingstatestring配送先の州または省。関連性と Shoppable Ads の注文履行に使用されます。
shippingzipcodestring配送先の郵便番号または郵便番号。関連性と Shoppable Ads の注文履行に使用されます。
shippingcountrystring配送先の国(ISO 3166-1 alpha-2)。関連性と Shoppable Ads の注文履行に使用されます。
partnerpaymentreferencestring顧客の保存された支払い方法の推測不可能な識別子。Shoppable Ads のカード転送に必要です。
last4digitsstring使用されたカードの最後の4桁。Shoppable Ads 中に顧客に表示されます。
plccstring"yes" または "no" — 顧客がプライベートラベルのクレジットカードを持っているかどうか。Pay+ の関連性に使用されます。
discountamountdecimal注文レベルの割引額。Pay+ の関連性に使用されます。
prescreenstring"yes" または "no" — 顧客がクレジットオファーの事前承認を受けているかどうか。Pay+ の関連性に使用されます。
adsexperiencestringShoppable Adsのエクスペリエンスを意図的に選択する場合は、"shoppable" を渡します。

イベント APIイベント API への直接リンク

SDK+ は、Rokt.events API を通じてプレースメントのライフサイクルイベントを発行します。ロード状態、エンゲージメント、失敗、Shoppable Adsの購入フローに応答するためにサブスクライブします。

Subscribe to Rokt.events
import mParticle_Apple_SDK

MParticle.sharedInstance().rokt.events("RoktLayout", onEvent: { roktEvent in
if let event = roktEvent as? RoktEvent.ShowLoadingIndicator {
// Example showing handling of ShowLoadingIndicator event
// The full list of events is provided below
}
})

標準イベント標準イベント への直接リンク

すべての標準イベントを表示
イベント説明パラメータ
ShowLoadingIndicatorSDK+ がRoktバックエンドを呼び出す前にトリガーされます
HideLoadingIndicatorSDK+ がRoktバックエンドから成功または失敗を受信したときにトリガーされます
PlacementInteractiveプレースメントがレンダリングされ、インタラクティブになったときにトリガーされますidentifier: String
PlacementReadyプレースメントが表示準備ができているが、まだコンテンツがレンダリングされていないときにトリガーされますidentifier: String
OfferEngagementユーザーがオファーにエンゲージしたときにトリガーされますidentifier: String
OpenUrlユーザーがパートナーアプリに送信するように設定されたURLを押したときにトリガーされますidentifier: String, url: String
PositiveEngagementユーザーがオファーに積極的にエンゲージしたときにトリガーされますidentifier: String
PlacementClosedユーザーによってプレースメントが閉じられたときにトリガーされますidentifier: String
PlacementCompletedオファーの進行が終了し、表示するオファーがなくなったときにトリガーされます。
キャッシュがヒットしたが、以前に却下されたために取得されたプレースメントが表示されない場合にもトリガーされます
identifier: String
PlacementFailure何らかの失敗によりプレースメントを表示できない場合、または表示するプレースメントがない場合にトリガーされますidentifier: String (optional)
FirstPositiveEngagementユーザーが初めてオファーに積極的にエンゲージしたときにトリガーされますidentifier: String, setFulfillmentAttributes: func (attributes: [String: String])
CartItemInstantPurchaseプレースメントを通じて購入が行われたときにトリガーされますidentifier: String, name: String?, cartItemId: String, catalogItemId: String, currency: String, description: String, linkedProductId: String?, providerData: String, quantity: NSDecimalNumber?, totalPrice: NSDecimalNumber?, unitPrice: NSDecimalNumber?
EmbeddedSizeChanged埋め込みプレースメントの高さが変わったときにトリガーされますidentifier: String, updatedHeight: CGFloat

Shoppable Ads イベントShoppable Ads イベント への直接リンク

Shoppable Ads イベントを表示
イベント説明パラメータ
CartItemInstantPurchaseInitiated購入フローが開始されました — ユーザーが「購入」をタップしましたidentifier, catalogItemId, cartItemId
CartItemInstantPurchase購入が正常に完了しましたidentifier, name, cartItemId, catalogItemId, currency, description, linkedProductId, providerData, quantity, totalPrice, unitPrice
CartItemInstantPurchaseFailure購入が失敗しましたidentifier, catalogItemId, cartItemId, error
CartItemDevicePayApple Pay / デバイス支払いがトリガーされましたidentifier, catalogItemId, cartItemId, paymentProvider
InstantPurchaseDismissalユーザーが購入オーバーレイを却下しましたidentifier
注記

Rokt Shoppable Adをリクエストした後、以下のいずれかのイベントが発行される可能性があり、Rokt Thanksの後続のリクエストを行うタイミングを判断するために使用されるべきです:

  • PlacementClosed
  • PlacementCompleted
  • PlacementFailure

7. Appendix#

Appendix A: アプリケーション設定Appendix A: アプリケーション設定 への直接リンク

アプリケーションは、RoktConfig を通じて設定を送信することで、iOS SDK+ がシステムのデフォルト設定ではなく、アプリのカスタム設定を使用するようにできます。

ColorMode オブジェクトColorMode オブジェクト への直接リンク

説明
lightアプリケーションはライトモードです
darkアプリケーションはダークモードです
systemアプリケーションはシステムのカラーモードにデフォルトします
ColorMode.light
// if application supports only Light Mode.
let roktConfig = RoktConfig.Builder().colorMode(.light).build()

MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes, embeddedViews: nil, config: roktConfig) { _ in }
ColorMode.light
// if application supports only Light Mode.
RoktConfig *roktConfig = [[[RoktConfigBuilder new] colorMode:RoktColorModeLight] build];

[[MParticle sharedInstance].rokt selectPlacements:@"RoktExperience"
attributes:attributes
embeddedViews:nil
config:roktConfig
onEvent:^(RoktEvent *_Nonnull event) {
// Handle placement events if needed
}];

CacheConfig オブジェクトCacheConfig オブジェクト への直接リンク

パラメータ説明
cacheDurationRokt SDK+ がエクスペリエンスをキャッシュするためのオプションの TimeInterval。許可される最大値は90分で、デフォルト(値が提供されていないか無効な場合)は90分です。
cacheAttributesキャッシュキーとして使用されるオプションの属性。nullの場合、selectPlacements 呼び出しで送信されたすべての属性がキャッシュキーとして使用されます。
Cache for 1200 seconds
// to cache the experience for 1200 seconds, using email and orderNumber attributes as the cache key.
let roktConfig = RoktConfig.Builder()
.cacheConfig(RoktConfig.CacheConfig(
cacheDuration: TimeInterval(1200),
cacheAttributes: ["email": "j.smith@example.com", "orderNumber": "123"]
))
.build()

MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes, embeddedViews: nil, config: roktConfig) { _ in }
Cache for 1200 seconds
// to cache the experience for 1200 seconds, using email and orderNumber attributes as the cache key.
NSDictionary *cacheKeyAttributes = @{
@"email": @"j.smith@example.com",
@"orderNumber": @"123"
};
RoktCacheConfig *cacheConfig =
[[RoktCacheConfig alloc] initWithCacheDuration:1200
cacheAttributes:cacheKeyAttributes];
RoktConfig *roktConfig = [[[RoktConfigBuilder new] cacheConfig:cacheConfig] build];

[[MParticle sharedInstance].rokt selectPlacements:@"RoktExperience"
attributes:attributes
embeddedViews:nil
config:roktConfig
onEvent:^(RoktEvent *_Nonnull event) {
// Handle placement events if needed
}];

Appendix B: SwiftUIサポートとMPRoktLayoutAppendix B: SwiftUIサポートとMPRoktLayout への直接リンク

アプリが主にSwiftUIで書かれている場合、iOSアプリにRoktプレースメントを統合するためのよりモダンな宣言的アプローチとして、MPRoktLayout コンポーネントを提供しています。

MPRoktLayout クラスは、selectPlacements を手動で呼び出すことなく、Roktプレースメントを表示するためのSwiftUI互換の方法を提供し、オーバーレイと埋め込みの両方のプレースメントタイプをサポートします。

SwiftUIコンポーネントの追加SwiftUIコンポーネントの追加 への直接リンク
SwiftUI placement with MPRoktLayout
import SwiftUI
import mParticle_Apple_SDK
import mParticle_Rokt_Swift

struct OrderConfirmationView: View {
let attributes = [
"email": "test@gmail.com",
"firstname": "Jenny",
"lastname": "Smith",
"billingzipcode": "07762",
"confirmationref": "54321"
]

@State private var sdkTriggered = true

var body: some View {
VStack(alignment: .leading) {
// Other UI components
Text("Order Confirmation")
.font(.title)

// Rokt placement using SwiftUI
MPRoktLayout(
sdkTriggered: $sdkTriggered,
identifier: "RoktExperience",
locationName: "RoktEmbedded1", // For embedded placements
attributes: attributes,
config: roktConfig, // Optional RoktConfig
onEvent: { roktEvent in
// Optional: Handle different event types see above
}
).roktLayout
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
}
パラメータパラメータ への直接リンク
パラメータ説明
sdkTriggeredBoolプレースメントをいつトリガーするかを制御します
identifierStringRoktプレースメント識別子(例: "RoktExperience")
locationNameString?埋め込みプレースメントのためのオプションのロケーション名(例: "RoktEmbedded1")
attributes[String: String]プレースメントに渡す属性の辞書
configRoktConfig?カラーモード、キャッシングなどのオプションの設定オブジェクト
onEvent((RoktEvent) -> Void)?すべてのプレースメントイベントを処理するためのオプションのコールバック

Appendix C: エラーハンドリングAppendix C: エラーハンドリング への直接リンク

IDSync APIはアプリの状態の中心となることを意図しており、高速で高可用性を備えています。アプリがインターネット接続なしでユーザーのログイン、ログアウト、または状態の変更を防ぐように、これらのAPIをゲート操作として扱い、一貫したユーザー状態を維持することを意図しています。SDK+はAPIコールを自動的に再試行しませんが、コールバックAPIを提供しているため、ビジネスロジックに従って再試行することができます。再試行や不整合な状態に対する許容度は、製品の要件に依存します。

エラーを処理しない場合、大規模なデータ整合性の問題が発生する可能性があります。実装中にエラーを監視することをお勧めします。

IDSyncコールバックブロックは、次の2つのオブジェクトのいずれかで呼び出されます:

  • MPIdentityApiResult: 新しいまたは更新されたユーザーオブジェクトを含む結果オブジェクト。
  • NSError/Error: IDSyncコールが失敗した場合にコードと説明を含むエラーオブジェクト
IDSync error handling
let identityCallback = {(result: MPIdentityApiResult?, error: Error?) in
if (result?.user != nil) {
//IDSync request succeeded, mutate attributes or query for the MPID as needed
result?.user.setUserAttribute("example attribute key", value: "example attribute value")
} else {
NSLog(error!.localizedDescription)
let resultCode = MPIdentityErrorResponseCode(rawValue: UInt((error! as NSError).code))
switch (resultCode!) {
case .clientNoConnection,
.clientSideTimeout:
//retry the IDSync request
break;
case .requestInProgress,
.retry:
//inspect your implementation if this occurs frequency
//otherwise retry the IDSync request
break;
default:
// inspect error.localizedDescription to determine why the request failed
// this typically means an implementation issue
break;
}
}
}
IDSync error handling
id identityCallback = ^(MPIdentityApiResult *_Nullable apiResult, NSError *_Nullable error) {
if (apiResult) {
// IDSync request succeeded, mutate attributes or query for the MPID as needed
[apiResult.user setUserAttribute:@"example attribute key"
value:@"example attribute value"];
} else {
NSLog(@"%@", error.userInfo);
switch (error.code) {
case MPIdentityErrorResponseCodeClientNoConnection:
case MPIdentityErrorResponseCodeClientSideTimeout:
// Retry the IDSync request
break;
case MPIdentityErrorResponseCodeRequestInProgress:
case MPIdentityErrorResponseCodeRetry:
// Inspect your implementation if this occurs frequently;
// otherwise retry the IDSync request
break;
default:
// Inspect error.userInfo to determine why the request failed
// This typically means an implementation issue
break;
}
}
};

ステータスコードステータスコード への直接リンク

IDSyncコールバックブロックが失敗で呼び出された場合、原因を特定するためにcodeプロパティを調べることができます。このプロパティは、それぞれのiOS SDK+ IDSync APIの呼び出し結果を説明することを目的としています。クライアント側で生成された値、または実際のHTTPステータスコードを含む場合があります。

クライアント側コードクライアント側コード への直接リンク

NSErrorコードプロパティは、MPIdentityErrorResponseCode列挙型内で定義された次のクライアント側コードを含む場合があります:

MPIdentityErrorResponseCode説明
MPIdentityErrorResponseCodeRequestInProgress既にIDSync HTTPリクエストが進行中のため、IDSync HTTPリクエストは実行されませんでした
MPIdentityErrorResponseCodeClientSideTimeoutTCP接続のタイムアウトにより、IDSync HTTPリクエストが失敗しました。
MPIdentityErrorResponseCodeClientNoConnectionネットワークカバレッジの欠如により、IDSync HTTPリクエストが失敗しました。
MPIdentityErrorResponseCodeSSLErrorSSL設定の問題により、IDSync HTTPリクエストが失敗しました。SDK+はmParticle SSL証明書をピン留めしており、無効化するにはMPNetworkOptions APIを介したカスタム初期化が必要です。
MPIdentityErrorResponseCodeOptOutオプトアウトによりSDK+が無効化されているため、IDSync HTTPリクエストは実行されませんでした。
MPIdentityErrorResponseCodeUnknown不明なエラーにより、IDSync HTTPリクエストが失敗しました。これは稀であり、アプリが不良メモリ状態にある可能性があります。

HTTPステータスコードHTTPステータスコード への直接リンク

NSErrorコードプロパティは、サーバー側で生成された次のHTTPステータスコードを含む場合があります。これらの一部は、利便性のためにMPIdentityErrorResponseCode列挙型内で定義されています:

説明
400無効なリクエストボディにより、IDSync HTTPコールが失敗しました。詳細については、error.userInfoオブジェクトを確認してください。
401認証エラーにより、IDSync HTTPコールが失敗しました。APIキーが正しいことを確認してください。
403この操作がアカウントに対してプロビジョニングされていないため、IDSync HTTPコールが失敗しました。有効化するにはRoktアカウントマネージャーに連絡してください。
429IDSync HTTPコールがスロットルされ、再試行する必要があります。これは、ユーザーの「ホットキー」または予想以上のIDSyncリクエスト量を引き起こす不正な実装を示している可能性があります。
5xxRoktサーバー側の問題により、IDSync HTTPコールが失敗しました。追加情報については、アカウント担当者に連絡してください。

UIApplication デリゲートプロキシUIApplication デリゲートプロキシ への直接リンク

デフォルトでは、mParticle SDK は UIApplication.delegate を独自の NSProxy 実装で置き換え、リモート通知、ローカル通知、通知アクションとのインタラクション、アプリケーションの起動の処理を容易にし、簡素化します。時間が経つにつれて、これは他の SDK が行うメソッドスウィズリングよりも侵襲性が低いことがわかっていますが、クライアントがサードパーティのフレームワークを使用している場合には複雑さを引き起こす可能性があります。

推奨事項

新しい統合では、proxyAppDelegate を無効にし、以下の SceneDelegate メソッド を使用してライフサイクルイベントを手動で mParticle に転送することをお勧めします。将来のメジャーリリースでは、proxyAppDelegate のデフォルトは false になります。

プロキシを無効にするには、proxyAppDelegate フラグを MParticleOptions オブジェクトで設定します。これを行うと、使用する各キットがどの UIApplication API を必要とするかを個別に監査する必要があります。必要なメソッドは mParticle で手動で呼び出し、mParticle がそれらの API を各キットに転送できるようにします。

let options = MParticleOptions(key: "REPLACE WITH APP KEY",
secret: "REPLACE WITH APP SECRET")
options.proxyAppDelegate = false
MParticle.sharedInstance().start(with: options)

プロキシが無効な場合の AppDelegate メソッドプロキシが無効な場合の AppDelegate メソッド への直接リンク

proxyAppDelegate が無効な場合、以下のメソッドを AppDelegate から mParticle に手動で転送する必要があります。これらのメソッドは、リモートまたはローカル通知機能を持つキット、およびプッシュ通知の登録に mParticle を使用するために必要です。

// MARK: - Remote Notification Registration

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
MParticle.sharedInstance().didRegisterForRemoteNotifications(withDeviceToken: deviceToken)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: any Error) {
MParticle.sharedInstance().didFailToRegisterForRemoteNotificationsWithError(error)
}

// MARK: - UNUserNotificationCenterDelegate

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
MParticle.sharedInstance().userNotificationCenter(center, willPresent: notification)
if #available(iOS 14, *) {
completionHandler([.list, .banner])
} else {
completionHandler(.alert)
}
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
MParticle.sharedInstance().userNotificationCenter(center, didReceive: response)
completionHandler()
}

SceneDelegate サポート (iOS 13+)SceneDelegate サポート (iOS 13+) への直接リンク

iOS 13で導入されたモダンなライフサイクルである UISceneDelegate を使用するアプリの場合、mParticleはURLコンテキストとユーザーアクティビティを処理するための専用メソッドを提供しています。これらはすべてのインテグレーションに推奨されるアプローチです。

URLコンテキストの処理URLコンテキストの処理 への直接リンク

SceneDelegate でディープリンクやカスタムURLスキームを処理するには、handleURLContext: メソッドを使用します:

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
for urlContext in URLContexts {
MParticle.sharedInstance().handleURLContext(urlContext)
}
}

SceneDelegate でユニバーサルリンクを処理するには、handleUserActivity: メソッドを使用します:

func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
MParticle.sharedInstance().handleUserActivity(userActivity)
}

付録 D: ウェブからネイティブへのセッションIDの引き渡し付録 D: ウェブからネイティブへのセッションIDの引き渡し への直接リンク

ユーザージャーニーがウェブとネイティブプラットフォームの両方にまたがる場合、Web SDK+からiOS SDK+にセッションIDを引き渡すことで、一貫したRoktセッションを維持できます。これは、ユーザーがWebView(支払いページなど)でアクションを完了し、確認のためにネイティブアプリに戻るハイブリッドフローに役立ちます。

Web SDK+からセッションIDを取得するWeb SDK+からセッションIDを取得する への直接リンク

selectPlacementsを呼び出した後、セッションIDは選択コンテキストで利用可能です:

Retrieve sessionId from the selection context
const selection = await launcher.selectPlacements({
identifier: "checkout",
attributes: {
email: "user@example.com",
// ... other attributes
}
});

const sessionId = await selection.context.sessionId;
注記

The session ID is a unique GUID assigned to the current user journey. It is useful for debugging and for correlating a user's activity across your web and native surfaces.

ディープリンクを使用して、セッションIDをネイティブアプリに渡します:

Deep-link to native app
const deepLink = `myapp://confirmation?sessionId=${encodeURIComponent(sessionId)}`;
window.location.href = deepLink;

セッションIDの設定セッションIDの設定 への直接リンク

ディープリンクからセッションIDを抽出し、selectPlacementsを呼び出す前にSDK+に渡します。

Handle deep link and set sessionId
func handleDeepLink(url: URL) {
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
if let sessionId = components?.queryItems?.first(where: { $0.name == "sessionId" })?.value {
MParticle.sharedInstance().rokt.setSessionId(sessionId: sessionId)
}

// Proceed with your confirmation flow
}
Handle deep link and set sessionId
- (void)handleDeepLink:(NSURL *)url {
NSURLComponents *components =
[NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
for (NSURLQueryItem *item in components.queryItems) {
if ([item.name isEqualToString:@"sessionId"]) {
[[[MParticle sharedInstance] rokt] setSessionIdWithSessionId:item.value];
break;
}
}

// Proceed with your confirmation flow
}

注意事項注意事項 への直接リンク

  • セッションが使用されることを確実にするために、setSessionIdselectPlacementsの前に呼び出します
  • 空の文字列は無視され、セッションを更新しません
  • クエリパラメータとして渡す際は、常にセッションIDをURLエンコードしてください

付録 E: Shoppable Adsの支払い設定付録 E: Shoppable Adsの支払い設定 への直接リンク

Shoppable Adsを使用していない場合、このステップはスキップしてください。

iOS上のShoppable Adsには登録済みのRoktPaymentExtensionが必要で、複数の支払い方法をサポートしています。リダイレクトベースの方法のみを提供する場合でも、すべてのShoppable Adsのプレースメントに対して拡張機能の登録が必須です。登録スニペットはステップ2の初期化コードに含まれています — MParticle.sharedInstance().start()の後、selectShoppableAdsの前に登録してください。

方法iOS設定
Apple PayApple PayのマーチャントIDをapplePayMerchantIdとしてRoktPaymentExtensionに渡します。オプションです。
PayPalRokt SDK+に組み込まれています — 追加の拡張設定は不要です。リダイレクトURLの転送が必要です(以下参照)。
Afterpay / ClearpayInfo.plistに登録されたカスタムURLスキーム + urlSchemeに一致するRoktPaymentExtension + リダイレクトURLの転送(以下参照)。
カード転送パートナー支払い共有API + partnerpaymentreference / last4digits属性をselectShoppableAdsで使用します。
注記

mParticle Rokt kit の設定で stripePublishableKey を設定します。このキーは自動的に Rokt に転送されます。Apple Pay はオプションです — Shoppable Ads は Apple Pay マーチャント ID なしでも、内蔵の PayPal およびカード転送をサポートしています。拡張機能を作成する際には、applePayMerchantId または urlScheme のいずれかを必ず提供する必要があります。

RoktPaymentExtension は Swift タイプであるため、Swift で作成および登録されます(Step 2 の Swift タブを参照)。Objective-C アプリの場合、小さな Swift ファイルからこれを行います。残りのフロー(selectShoppableAds, handleURLCallback)は Objective-C から利用可能です。

Apple Pay(オプション)Apple Pay(オプション) への直接リンク

Apple Pay を提供するには、Apple Pay マーチャント ID を作成し、Xcode プロジェクトを設定し、Payment Processing Certificate を生成します。Apple Pay — iOS setup の手順に従い、applePayMerchantId としてマーチャント ID を RoktPaymentExtension 作成時に渡します。

Afterpay / Clearpay(オプション)Afterpay / Clearpay(オプション) への直接リンク

Afterpay および Clearpay はリダイレクトベースです。これらを有効にするには:

  1. アプリの Info.plistCFBundleURLTypes の下で URL スキームを登録します(例: myapp)。
  2. RoktPaymentExtension 作成時に一致する urlScheme を渡します(例: "myapp")。SDK は内部でリターン URL を構築します。
  3. リダイレクト URL を Rokt に転送します — 以下を参照。

リダイレクト URL の転送リダイレクト URL の転送 への直接リンク

Afterpay、Clearpay、および PayPal は、顧客を Web ビューに送り、登録された URL スキームを介してアプリにリダイレクトします。既存の mParticle URL ハンドリングに加えて、handleURLCallback を使用して Rokt に受信 URL を転送します。

Forward redirect URLs (SceneDelegate)
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
for urlContext in URLContexts {
if MParticle.sharedInstance().rokt.handleURLCallback(with: urlContext.url) {
return
}
MParticle.sharedInstance().handleURLContext(urlContext)
}
}
Forward redirect URLs (SwiftUI)
WindowGroup {
ContentView()
.onOpenURL { url in
_ = MParticle.sharedInstance().rokt.handleURLCallback(with: url)
}
}

8. Test Your Integration#

SDK+ が正しく初期化され、イベントが正しくログに記録されることを確認するには:

1Enable verbose SDK+ logging#

初期化前に詳細な SDK+ ロギングを有効にして、送信されている内容を確認します。

Enable verbose SDK+ logging
Rokt.setLoggingEnabled(enable: true)

2Build and run against a development key#

開発キーでアプリをビルドして実行し、environment = .development(または MPEnvironmentDevelopment)を使用します。

3Trigger selectPlacements#

配置がレンダリングされるべき画面で selectPlacements をトリガーし、配置が読み込まれることを確認します。

4Verify events#

イベントがログに記録され、identifyRequest 呼び出しが成功することを確認します。

トラブルシューティングトラブルシューティング への直接リンク

配置がレンダリングされない、またはイベントが表示されない場合は、Xcode コンソールで Rokt SDK+ のエラーを確認してください。一般的な問題は以下の通りです:

初期化エラー初期化エラー への直接リンク

  • keysecret が Rokt アカウントマネージャーからの値と一致していることを確認してください。
  • MParticle.sharedInstance().start(with: options)selectPlacementslogEvent の呼び出しの前に実行されていることを確認してください。
  • ショッパブル広告の場合、RoktPaymentExtensionstart() の後、selectShoppableAds の前に登録されていることを確認してください。PayPal または Afterpay / Clearpay を使用している場合は、handleURLCallback が URL ハンドラーに組み込まれていることを確認してください。

アイデンティティエラーアイデンティティエラー への直接リンク

onIdentifyComplete またはアイデンティティコールバックがエラーで発火し、ユーザーが返されない場合は、エラーハンドリング を参照して MPIdentityErrorResponseCode の値と再試行ガイダンスを確認してください。エラーハンドリングがないと、大規模なデータ整合性の問題が発生する可能性があります。

配置がレンダリングされない配置がレンダリングされない への直接リンク

  • 配置の identifier(例:RoktExperience)が Rokt アカウントマネージャーが設定したものと一致していることを確認してください。
  • 埋め込み配置の場合、埋め込みビュー識別子(例:RoktEmbedded1)がレイアウト設定と一致していることを確認してください。
  • 属性辞書に少なくとも emailfirstnamelastnamebillingzipcodeconfirmationref が含まれていることを確認してください。

プロキシ使用時のSSLハンドシェイクエラープロキシ使用時のSSLハンドシェイクエラー への直接リンク

開発環境でテスト中に、Charles や Proxyman などの HTTP デバッグプロキシが実行されている場合、または企業ネットワークプロキシの背後にいる場合、SSL ハンドシェイクエラーが発生することがあります。SDK+ が現在のユーザーを識別しようとすると、これは MPIdentityErrorResponseCodeSSLError として報告されます(エラーハンドリング を参照)。これは予期された動作です:SDK+ はその SSL 証明書をピン留めしており、プロキシは独自の証明書を提示することで HTTPS を傍受し、ピン留めに失敗します。

プロキシが SDK+ トラフィックを検査できるようにするには、pinningDisabledInDevelopmentMPNetworkOptions に設定して開発ビルドでピン留めを無効にします。SDK+ 初期化スクリプト を参照してください。

Disable SSL pinning for proxy debugging
let networkOptions = MPNetworkOptions()
// Only takes effect in the development environment; production builds stay pinned.
networkOptions.pinningDisabledInDevelopment = true
options.networkOptions = networkOptions
この記事は役に立ちましたか?