Integrasi SDK AppsFlyer - iOS

  • Pengiklan
  • Pengembang

ios.pngSDK Version: 4.9.0 (Release notes)

1. Garis Besar

Panduan ini menjelaskan cara pengintegrasian SDK AppsFlyer ke aplikasi iOS. Anda dapat melacak instalasi, pembaruan, sesi, dan event dalam-aplikasi tambahan serta instalasi aplikasi (termasuk pembelian dalam-aplikasi, tingkat permainan, dll.) untuk mengevaluasi tingkat pulangan (ROI) dan tingkat interaksi pengguna. SDK iOS kompatibel dengan semua perangkat iOS (iPhone, iPod, iPad) dengan iOS versi 6 dan di atasnya.

 Catatan

SDK AppsFlyer sepenuhnya mematuhi Jaringan IPv6 DNS64/NAT64 milik Apple. Untuk informasi lebih lanjut, klik di sini.

 Penting!

SDK AppsFlyer memanfaatkan kelas NSUserDefaults. Menghapus semua data dari NSUserDefaults dapat menyebabkan masalah atribusi.

 Tips

  • Chapters 2 and 3 are MANDATORY to implement BASIC SDK integration, i.e. install attribution only
  • Tracking in-app events chapter is HIGHLY RECOMMENDED to implement
  • The rest of the described features are OPTIONAL to implement, although some of them may be necessary for you, depending on your app's business logic. For example, tracking revenue or getting the conversion data on first launch may be vital for your app's flow

2. Mulai

2.1 Mengunduh dan menambahkan SDK AppsFlyer ke Xcode

CocoaPodsCarthageStatic FrameworkStatic Lib
  • Pastikan Anda telah mengunduh dan menginstal CocoaPods versi terbaru.
  • Add the following row to your Podfile:
    pod 'AppsFlyerFramework'
  • jalankan pod install
  • Pastikan Anda menggunakan file .xcworkspace untuk membuka proyek dalam Xcode, bukan menggunakan file .xcodeproj mulai sekarang.

SDK AppsFlyer menggunakan framework asli berikut:

AdSupport.framework
This framework is required to collect the IDFA from devices.
Without IDFA you cannot track Facebook Ads, Twitter, Google ads and other networks.
iAd.framework
Framework ini diperlukan untuk melacak Iklan Pencarian Apple di aplikasi Anda

2.2 Mengonfigurasi Integrasi di dalam Delegasi Aplikasi

Buka file AppDelegate.m aplikasi Anda dan impor SDK AppsFlyer:

SwiftObjective-C
impor AppsFlyerLib

3. Inisiasi SDK

Initialize the SDK in the didFinishLaunchingWithOptions method with your app ID taken from iTunes Connect and your AppsFlyer dev key.

Harap diperhatikan bahwa Anda perlu mengatur app ID hanya dengan angka, tanpa awalan "id".

SwiftObjective-C
AppsFlyerTracker.shared().appsFlyerDevKey = "<your-appsflyer-dev-key>";
AppsFlyerTracker.shared().appleAppID = "123456789"
AppsFlyerTracker.shared().delegate = self
#if DEBUG AppsFlyerTracker.shared().isDebug = true
#endif

 Catatan

Log SDK AppsFlyer akan ditampilkan di Konsol xCode jika isDebug=true telah diatur

 

  • Tambahkan kode berikut pada fungsi applicationDidBecomeActive:
SwiftObjective-C
func applicationDidBecomeActive(application: UIApplication) { 
// Track Installs, updates & sessions(app opens) (You must include this API to enable tracking) 
AppsFlyerTracker.shared().trackAppLaunch() 
// your other code here.... }

4. Melacak Event Dalam-Aplikasi

Event Dalam-Aplikasi memberikan informasi tentang hal yang terjadi dalam aplikasi Anda. Sebaiknya luangkan waktu dan tentukan event yang ingin Anda ukur agar Anda dapat melacak ROI (Return on Investment) dan LTV (Lifetime Value).

Mengukur in-app event dilakukan dengan cara memanggil fungsi trackEvent bersama nama event dan nilai parameternya. Lihat In-App Event untuk keterangan detail.

Nama event dalam-aplikasi tidak boleh lebih dari 45 karakter. Nama Event yang melebihi 45 karakter tidak muncul di dashboard, namun hanya tertera di laporan data lengkap, API Pull dan API Push.

Example: Purchase In-App Event

SwiftObjective-C
AppsFlyerTracker.shared().trackEvent(AFEventPurchase,
  withValues: [
     AFEventParamRevenue: "1200",
     AFEventParamContent: "shoes",
     AFEventParamContentId: "123"
]);

This generates an af_purchase event type (using the AFEventPurchase constant) with the following event values: {af_revenue: 200 , af_currency: "USD", af_quantity: 2, af_content_id: "092" af_receipt_id: "9277"}

 Catatan

AppsFlyer mendukung karakter non-Inggris dalam in-app event, atau dengan SDK API lainnya, mulai dari SDK iOS versi 4.8.1.

For revenue, do not add any currency symbols as these are not recognized.

 Contoh Penggunaan

SwiftObjective C
AppsFlyerTracker.shared().trackEvent(AFEventPurchase,
withValues: [
  AFEventParamRevenue: @1200,
  AFEventParamCurrency : @"JPY"
]); 

5. Melacak Deep Linking

 Tips

We highly recommend having deep linking integrated in your app. Deep Linking is a crucial part of retargeting campaigns and it is highly recommended to use when running retargeting campaigns.

iOS 9 dan di atasnya memerlukan aplikasi yang mendukung Universal Links. Untuk informasi lebih lanjut, klik di sini.


To handle deep linking, add the following code in your app (in the app delegate class). The methods in this code allow you to get deep linking data. With deep linking data you can redirect users to the relevant app activity and serve them with the relevant content.

SwiftObjective-C

 func onConversionDataReceived(_ installData: [AnyHashable: Any]) {
  //Handle Conversion Data (Deferred Deep Link)
  }
  
  func onConversionDataRequestFailure(_ error: Error?) {
    //    print("\(error)")
  }
  
  func onAppOpenAttribution(_ attributionData: [AnyHashable: Any]) {
    //Handle Deep Link Data
    
  }
  
  func onAppOpenAttributionFailure(_ error: Error?) {
  }
// Reports app open from a Universal Link for iOS 9 or later
  func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
    AppsFlyerTracker.shared().continue(userActivity, restorationHandler: restorationHandler)
    return true
  }

  // Reports app open from deep link from apps which do not support Universal Links (Twitter) and for iOS8 and below
  func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    AppsFlyerTracker.shared().handleOpen(url, sourceApplication: sourceApplication, withAnnotation: annotation)
    return true
  }

  // Reports app open from deep link for iOS 10 or later
  func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    AppsFlyerTracker.shared().handleOpen(url, options: options)
    return true
  }
  

 Penting!

For Swift 4.2 and above, use the following code for the continue userActivity method:

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
	AppsFlyerTracker.shared().continue(userActivity, restorationHandler: nil)
	return true
}

6. Melacak Pendapatan

Use the af_revenue (AFEventParamRevenue) event parameter to count revenue as part of an in-app event. You can populate it with any numeric value, positive or negative.

 Catatan

AFEventParamRevenue (equivalent to using af_revenue) is the ONLY event parameter that is counted on AppsFlyer as real revenue on the raw data and dashboard. For more details please click here.


Contoh: Pendapatan dari event didalam aplikasi

SwiftObjective-C
AppsFlyerTracker.shared().trackEvent(AFEventPurchase, 
withValues: [
	AFEventParamContentId:"1234567",
	AFEventParamContentType : "category_a",
	AFEventParamRevenue: 1.99,
	AFEventParamCurrency:"USD"
]);

 Penting!

Do NOT format the revenue value in any way. It should not contain comma separators, currency sign, or text. A revenue event should be similar to 1234.56, for example.

Tracking Negative Revenue

If you need to track negative revenue for example when a user cancels a purchase or receives a refund, you can send negative revenue.

SwiftObjective-C
AppsFlyerTracker.shared().trackEvent("cancel_purchase", 
withValues: [
	AFEventParamContentId:"1234567",
	AFEventParamContentType : "category_a",
	AFEventParamRevenue: -1.99,
	AFEventParamCurrency:"USD"
]);

 Catatan

Notice the following in the code above:

  1. The revenue value is preceded by a minus sign
  2. The event name has a unique value of "cancel_purchase" - to allow you to identify negative revenue events in the dashboard and raw data reports

7. Memperoleh Data Konversi

AppsFlyer allows you to access the user attribution data in real-time for every new install, directly from the SDK level. By doing this you can serve users with personalized content or send them to specific activities within the app, which can greatly enhance their engagement with your app.

Untuk informasi lebih lanjut tentang fungsi ini, klik di sini.

8. Pengidentifikasi Pengguna

Ada beberapa pilihan untuk memperoleh pengidentifikasi pengguna:

Memperoleh AppsFlyer Device ID

AppsFlyer Device ID dibuat untuk setiap instalasi aplikasi baru. Anda dapat memperolehnya dengan menggunakan kode berikut:

SwiftObjective-C
let appsflyerId = AppsFlyerTracker.shared().getAppsFlyerUID()

Mengatur ID Pengguna Pelanggan

Dengan mengatur ID pelanggan Anda sendiri, Anda dapat membandingkan ID pelanggan Anda dengan ID unik AppsFlyer dan ID perangkat lainnya. ID ini tersedia di laporan data lengkap AppsFlyer bersama dengan API Postback untuk memandingkan dengan ID internal Anda.

Cara mengatur ID Pengguna Pelanggan Anda:

SwiftObjective-C
AppsFlyerTracker.shared().customerUserID = "my user id"

 Catatan Penting

It is recommended to set your Customer User ID as soon as possible as it is only associated to events reported after its setup. If setCustomerUserId is called before calling trackAppLaunch, the Customer User ID is visible in the raw export for installs and for events. If it is set after, only the value for events tracked is visible after calling this method.

ID User Kustomer dapat juga digunakan untuk melengkapi integrasi dengan platform Analisis seperti Mixpanel dan Swrve.

Memperoleh ID Pengguna Pelanggan:

To get the customer user ID retrieve it from the sharedTracker.

[AppsFlyerTracker sharedTracker].customerUserID

 Penting!

Make sure to set the customer user ID each time the app is launched, before calling trackAppLaunch</code.

Untuk informasi lebih lanjut tentang Customer User ID, klik di sini.

IDFA dan IDFV

AppsFlyer secara otomatis mengumpulkan IDFA (ID Untuk Pengiklan) dan IDFV (ID Untuk Vendor) jika AdSupport.framework dimuat di aplikasi.

9. Fitur Pilihan

Measure Uninstalls

For Uninstall measurement, enable remote push notification on your app. See Apple's Remote Notification Programming Guide for more details.

Follow the iOS SDK integration instructions to complete the uninstall measurement feature setup.

Melacak Push Notification

Untuk mengaktifkan Pengukuran aplikasi dibuka dari push notification, tambahkan kode berikut ke delegasi aplikasi:

SwiftObjective-C
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
	AppsFlyerTracker.shared().handlePushNotification(userInfo)
}

Push Notification harus memiliki parameter af dengan parameter pelacakan AppsFlyer.

Contoh Pesan:

{
  "aps":{
   "alert":"Push text",
   "sound":"default",
   "category":"REMINDER_CATEGORY"
  },
  "_p":123456,
  "payloadKey":"payloadValue",
  "af":{
   "pid":"swrve_int",
   "is_retargeting":"true",
   "c":"test_campaign"
  }
}

Pelacakan Promosi Silang

AppsFlyer allows you to track and attribute installs originating from a cross promotion of one of your apps from within the current app the user has. Cross promoting apps can be a major growth factor in driving additional installs for your apps.

For details, see the Cross Promotion Tracking article, here.

Pelacakan Undangan Pengguna

AppsFlyer allows you to track and attribute installs originating from user invites within your app. Allowing your existing users to invite their friends and contacts as new users to your app can be a key growth factor for your app.
 
For details, see the User Invite Tracking article, here.

Mengatur Kode Mata Uang

You can set a global currency code using the API below, in addition to specific currency codes that can be used as part of each in-app event sent to AppsFlyer. The global currency code is used when AFEventParamCurrency is not sent as part of an in-app event.

Nilai default adalah USD. Anda dapat melihat kode mata uang ISO yang dapat diterima di sini.

Gunakan API berikut untuk mengatur kode mata uang:

public void currencyCode(String currencyCode);

Contoh Penggunaan:

SwiftObjective-C
Appsflyertracker.shared().currencycode = "USD"

Validasi Pembelian Dalam-Aplikasi

 Catatan

Fungsi ini didukung untuk iOS 7 dan di atasnya.

AppsFlyer’s SDK can provide in‐app purchase server verification. To set receipt validation tracking you need to call the validateAndTrackInAppPurchase method inside the SKStoreKit’s completeTransaction: callback. This call automatically generates an af_purchase in‐app event.

- (void) validateAndTrackInAppPurchase:(NSString *) productIdentifier
price:(NSString *) price
currency:(NSString *) currency
transactionId:(NSString *) tranactionId
additionalParameters:(NSDictionary *) params
success:(void (^)(NSDictionary *response)) successBlock
failure:(void (^)(NSError *error, id reponse)) failedBlock;

 Catatan

The price parameter should contain the total revenue associated with the validated purchase event.


This call has two callback blocks, one for ‘success’ and one for ‘failure’ (for any reason, including validation fail). On success, a dictionary is returned with the receipt validation data provided by Apple’s servers.

 Penting

For testing purposes, we recommend setting the useReceiptValidationSandbox flag to YES, as this redirects the requests to Apple sandbox servers.

#ifdef DEBUG
[AppsFlyerTracker sharedTracker].useReceiptValidationSandbox = YES;
#endif

 

 Contoh

Objective-CSwift
[[AppsFlyerTracker sharedTracker] validateAndTrackInAppPurchase:@"ProductIdentifier" price:@"price"
    currency:@"USD"
    transactionId:@"transactionID"
    additionalParameters:@{@"test": @"val" , @"test1" : @"val 1"}
    success:^(NSDictionary *result){
      NSLog(@"Purchase succeeded And verified!!! response: %@", result[@"receipt"]);
    } failure:^(NSError *error, id response) {
      NSLog(@"response = %@", response);
      if([response isKindOfClass:[NSDictionary class]]) {
        if([response[@"status"] isEqualToString:@"in_app_arr_empty"]){
          // retry with 'SKReceiptRefreshRequest' because
          // Apple has returned an empty response
          // <YOUR CODE HERE>
        }

      } else {
        //handle other errors
        return;
      }
  }];

 Penting!

When AppsFlyer validates a purchase against Apple servers, if the response contains an empty in-app array, AppsFlyer returns {"status":"in_app_arr_empty"} to the error callback.

If you receive this flag, you must restore the purchased product with Apple by sending a receipt refresh request. For more information see Apple's documentation.

After refreshing the receipt, call validateAndTrackInAppPurchase once more.

See the code above to learn how to handle this error.

For a list of possible return values for validating receipts, please refer to Apple's documentation here.

Penganoniman

AppsFlyer provides you with a method to anonymize specific user identifiers in AppsFlyer analytics. This method complies with the latest privacy requirements and complies with Facebook data and privacy policies. Default is NO, meaning no anonymization is performed by default.

Gunakan API ini saat inisialisasi SDK untuk menganonimkan instalasi,event dan sesi pengguna secara eksplisit:

SwiftObjective-C
AppsFlyerTracker.shared().deviceTrackingDisabled = true

Pengukuran dapat diulang dengan memanggil kembali deviceTrackingDisabled dan mengaturnya ke false.

 Peringatan

Anonymizing users SEVERELY impacts your attribution information.
Use this option ONLY for regions which legally prevent you from collecting your users' information.

Mengganti Waktu Antar Sesi

By default, at least 5 seconds must lapse between 2 app launches to count as separate 2 sessions (more about counting sessions).
However, you can use the following API to set your custom value for the minimum required time between sessions:

SwiftObjective-C
AppsFlyerTracker.shared().minTimeBetweenSessions = <your_custom_time_in_seconds>

Note that setting a high value to the custom time between launches may badly impact APIs relying on sessions data, such as deep linking.

Sesi Latar Belakang untuk Aplikasi Utilitas

Unavailable in iOS.
 

Ekstensi Aplikasi iOS dan WatchKit

Ekstensi aplikasi ini memerlukan hak akses untuk menggunakan Internet:

  1. Silakan buka file info.plist ekstensi aplikasi Anda
  2. Pada NSExtension / NSExtensionAttributes atur bendera RequestsOpenAccess ke YES.

Tambahkan kode berikut ke UIViewController ekstensi aplikasi viewDidLoad:

SwiftObjective-C
override func viewDidLoad() {  
    super.viewDidLoad()
    AppsFlyerTracker.shared().appsFlyerDevKey = "MY_APPSFLYER_KEY"

    // MY_APP_ID below stands for you app ID on iTunes Connect. Should be 9 or 10 digits.
    AppsFlyerTracker.shared().appleAppID = "MY_APP_ID"
        
    AppsFlyerTracker.sharedTracker().trackAppLaunch()
  }

Untuk menerima data atribusi pada ekstensi aplikasi, ikuti instruksi di sini dan terapkan pada UIViewController aplikasi Anda, bukan pada AppDelegate.

Opt-Out

In some extreme cases you might want to shut down all SDK tracking due to legal and privacy compliance. This can be achieved with the isStopTracking API. Once this API is invoked, our SDK no longer communicates with our servers and stops functioning.

Ada beberapa skenario berbeda untuk berhenti mengirim data user. Kami menyarankan anda untuk mengikuti instruksi yang sesuai dan relevan untuk app Anda.

 Peringatan

Use this API only in cases where you want to fully ignore this user from any and all tracking. Using this API SEVERELY impacts your attribution, data collection and deep linking mechanism.

SwiftObjective-C
AppsFlyerTracker.shared().isStopTracking = true

 Penting

Jangan panggil trackAppLaunch jika isStopTracking diatur ke true

Mengumpulkan Nama Device

SDK AppsFlyer mengizinkan Anda untuk mengumpulkan Nama Perangkat untuk analisis internal Anda. Dalam aturan standar, fitur ini dinonaktifkan. Gunakan API berikut untuk mengaktifkan:

SwiftObjective-C
>AppsFlyerTracker.shared().shouldCollectDeviceName = false`

 Penting

Nama Perangkat dianggap Data Pribadi di wilayah tertentu. Kumpulkan informasi ini hanya jika Anda diizinkan secara hukum dan telah menerima persetujuan secara eksplisit dari pengguna untuk melakukannya.

Mengatur Data Kustom Tambahan

The setAdditionalData API is required to integrate on the SDK level with several external partner platforms, including Segment, Adobe and Urban Airship. Use this API only if the integration article of the platform specifically states setAdditionalData API is needed.
The following is a code example for implementing setAdditionalData on iOS for Objective-C or Swift

Objective-CSwift
NSDictionary* CustomDataMap = [[NSDictionary alloc] initWithObjectsAndKeys:@"value_of_param_1", @"custom_param_1", nil];
  
[[AppsFlyerTracker sharedTracker] setAdditionalData:CustomDataMap];

Resolving Wrapped Deep Link URLs

If you are using OneLinks which support Universal Links and wrapping them with a 3rd Party Universal Link, you can use the setResolveDeepLinkURLs API to notify the AppsFlyer SDK which click domains that invoke the app should be resolved by the SDK and have the underlying OneLink extracted from them. This will allow you to maintain deep linking and tracking while wrapping the OneLink with a 3rd party Universal Link. Make sure to call this API before SDK initialization.

Objective-CSwift
[AppsFlyerTracker sharedTracker].resolveDeepLinkURLs = @[@"example.com",@"click.example.com"];

10. Menguji Integrasi Anda

Untuk informasi lebih lanjut tentang cara menguji integrasi Anda, klik di sini.

Now you can start tracking the media sources you work with.

11. Mengirimkan Aplikasi ke App Store

Anda dapat melihat instruksi cara mengirimkan aplikasi Anda ke App Store di sini.

Apakah artikel ini membantu?
9 dari 14 menganggap ini berguna

Komentar

0 komentar

Harap login untuk memberikan komentar.

Artikel dalam bagian ini

Isi Halaman: