Affise Attribution iOS Library
| Pod | Version |
|---|---|
AffiseAttributionLib |
1.6.9 |
AffiseSKAdNetwork |
1.6.9 |
AffiseModule/Status |
1.6.9 |
- Affise Attribution iOS Library
- Description
- Features
Description
Affise SDK is a software you can use to collect app usage statistics, device identifiers, deeplink usage, track install referrer.
Quick start
Integration
Integrate as Cocoapods
To add the SDK using Cocoapods, specify the version you want to use in your Podfile:
# Affise SDK library
pod 'AffiseAttributionLib', '~> 1.6.9'
# Affise module
pod 'AffiseModule/Status', '~> 1.6.9'Get source directly from GitHub
# Affise SDK library
pod 'AffiseAttributionLib', :git => 'https://github.com/affise/sdk-ios.git', :tag => '1.6.9'
# Affise module
pod 'AffiseModule/Status', :git => 'https://github.com/affise/sdk-ios.git', :tag => '1.6.9'Initialize
After library is added as dependency sync project with gradle files and initialize.
For swift use:
Demo app AppDelegate.swift
import AffiseAttributionLib
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let properties = AffiseInitProperties(
affiseAppId: "Your appId", //Change to your app id
secretKey: "Your secretKey" //Change to your appToken
)
Affise.shared.load(app: application, initProperties: properties, launchOptions: launchOptions)
return true
}
}For objective-c use:
Demo app AppDelegate.m
#import "AppDelegate.h"
#import <AffiseAttributionLib/AffiseAttributionLib-Swift.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
AffiseInitProperties *initProperties = [[AffiseInitProperties alloc]
initWithAffiseAppId:@"Your appId" //Change to your app id
secretKey:@"Your secretKey" //Change to your appToken
];
[Affise.shared loadWithApp:application initProperties:initProperties launchOptions:launchOptions];
return YES;
}
@endCheck if library is initialized
Affise.shared.isInitialized()StoreKit Ad Network
To add the SDK using Cocoapods, specify the version you want to use in your Podfile:
# Wrapper for StoreKit Ad Network
pod 'AffiseSKAdNetwork', '~> 1.6.9'Get source directly from GitHub
# Wrapper for StoreKit Ad Network
pod 'AffiseSKAdNetwork', :git => 'https://github.com/affise/sdk-ios.git', :tag => '1.6.9'For use:
For ios prior 15.4
import AffiseSKAdNetwork
AffiseSKAdNetwork.shared()?.registerAppForAdNetworkAttribution(completionHandler: { error in
// Handle error
})
AffiseSKAdNetwork.shared()?.updateConversionValue(conversionValue, completionHandler: { error in
// Handle error
})For ios 15.4
import AffiseSKAdNetwork
AffiseSKAdNetwork.shared()?.updatePostbackConversionValue(fineValue, completionHandler: { error in
// Handle error
})For ios 16.1
import AffiseSKAdNetwork
AffiseSKAdNetwork.shared()?.updatePostbackConversionValue(fineValue, coarseValue, completionHandler: { error in
// Handle error
})Configure your app to send postback copies to Affise:
Add key NSAdvertisingAttributionReportEndpoint to Info.plist
Set key value to https://affise-skadnetwork.com/
Example: example/ios/Runner/Info.plist
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>NSAdvertisingAttributionReportEndpoint</key>
<string>https://affise-skadnetwork.com/</string>
</dict>
</array>Features
Device identifiers collection
To match users with events and data library is sending, these identifiers are collected:
AFFISE_APP_IDAFFISE_PKG_APP_NAMEAPP_VERSIONAPP_VERSION_RAWSTOREINSTALLED_TIMEFIRST_OPEN_TIMEINSTALLED_HOURFIRST_OPEN_HOURINSTALL_BEGIN_TIMEINSTALL_FINISH_TIMEREFERRAL_TIMECREATED_TIMECREATED_TIME_MILLICREATED_TIME_HOURUNINSTALL_TIMEREINSTALL_TIMELAST_SESSION_TIMECONNECTION_TYPECPU_TYPEHARDWARE_NAMENETWORK_TYPEDEVICE_MANUFACTURERPROXY_IP_ADDRESSDEEPLINK_CLICKDEVICE_ATLAS_IDAFFISE_DEVICE_IDAFFISE_ALT_DEVICE_IDADIDANDROID_IDANDROID_ID_MD5MAC_SHA1MAC_MD5GAID_ADIDGAID_ADID_MD5OAIDOAID_MD5REFTOKENREFTOKENSREFERRERUSER_AGENTMCCODEMNCODEISPREGIONCOUNTRYLANGUAGEDEVICE_NAMEDEVICE_TYPEOS_NAMEPLATFORMAPI_LEVEL_OSAFFISE_SDK_VERSIONOS_VERSIONRANDOM_USER_IDAFFISE_SDK_POSTIMEZONE_DEVLAST_TIME_SESSIONTIME_SESSIONAFFISE_SESSION_COUNTLIFETIME_SESSION_COUNTAFFISE_DEEPLINKAFFISE_PART_PARAM_NAMEAFFISE_PART_PARAM_NAME_TOKENAFFISE_APP_TOKENLABELAFFISE_SDK_SECRET_IDUUIDAFFISE_APP_OPENEDPUSHTOKENEVENTSAFFISE_EVENTS_COUNT
Events tracking
For example, we want to track what items usually user adds to shopping cart. To send event first create it with following code
class Presenter {
func onUserAddsItemsToCart(items: String) {
let items = [
("items", "cookies, potato, milk")
]
Affise.shared.sendEvent(event: AddToCartEvent("groceries")
.addPredefinedParameter(PredefinedString.DESCRIPTION, string: "best before 2029")
.addPredefinedParameter(PredefinedObject.CONTENT, object: items)
)
}
}For objective-c use:
- (void)onUserAddsItemsToCart:(NSString *)itemsToCart {
NSArray *items = @[
@{"items", itemsToCart}
];
Event *event = [[AddToCartEvent alloc] init:@"groceries"];
[event addPredefinedParameter:PredefinedStringADREV_AD_TYPE value:@"best before 2029"];
[event addPredefinedParameter:PredefinedObjectCONTENT object:items];
[Affise.shared sendEventWithEvent: event];
}With above example you can implement other events:
AchieveLevelAddPaymentInfoAddToCartAddToWishlistClickAdvCompleteRegistrationCompleteStreamCompleteTrialCompleteTutorialContactContentItemsViewCustomizeProductDeepLinkedDonateFindLocationInitiateCheckoutInitiatePurchaseInitiateStreamInviteLastAttributedTouchLeadListViewLoginOpenedFromPushNotificationOrderOrderCancelOrderReturnRequestOrderReturnRequestCancelPurchaseRateReEngageReserveSalesScheduleSearchShareSpendCreditsStartRegistrationStartTrialStartTutorialSubmitApplicationSubscribeTravelBookingUnlockAchievementUnsubscribeUpdateViewAdvViewCartViewContentViewItemViewItemsInitialSubscriptionInitialTrialInitialOfferConvertedTrialConvertedOfferTrialInRetryOfferInRetrySubscriptionInRetryRenewedSubscriptionFailedSubscriptionFromRetryFailedOfferFromRetryFailedTrialFromRetryFailedSubscriptionFailedOfferiseFailedTrialReactivatedSubscriptionRenewedSubscriptionFromRetryConvertedOfferFromRetryConvertedTrialFromRetryUnsubscription
Custom events tracking
Use any of custom events if default doesn't fit your scenario:
CustomId01CustomId02CustomId03CustomId04CustomId05CustomId06CustomId07CustomId08CustomId09CustomId10
Predefined event parameters
To enrich your event with another dimension, you can use predefined parameters for most common cases. Add it to any event:
class Presenter {
func onUserAddsItemsToCart(items: String) {
let items = [
("items", "cookies, potato, milk")
]
let addToCart = AddToCartEvent("groceries")
.addPredefinedParameter(PredefinedString.DESCRIPTION, string: "best before 2029")
.addPredefinedParameter(PredefinedObject.CONTENT, object: items)
Affise.shared.sendEvent(event: addToCart)
}
}For objective-c use:
- (void)onUserAddsItemsToCart:(NSString *)itemsToCart {
NSArray *items = @[
@{"items", itemsToCart}
];
Event *event = [[AddToCartEvent alloc] init:@"groceries"];
[event addPredefinedParameter:PredefinedStringADREV_AD_TYPE value:@"best before 2029"];
[event addPredefinedParameter:PredefinedObjectCONTENT object:items];
[Affise.shared sendEventWithEvent: event];
}In examples above PredefinedParameters.DESCRIPTION and PredefinedObject.CONTENT is used, but many others is available:
| PredefinedParameter | Type |
|---|---|
| PredefinedString | String |
| PredefinedLong | Int64 |
| PredefinedFloat | Float |
| PredefinedObject | [(String, Any)] |
| PredefinedListObject | [[(String, Any)]] |
| PredefinedListString | [String] |
PredefinedString
ACHIEVEMENT_IDADREV_AD_TYPEBRANDBRICKCATALOGUE_IDCHANNEL_TYPECITYCLASSCONTENT_IDCONTENT_NAMECONTENT_TYPECONVERSION_IDCOUNTRYCOUPON_CODECURRENCYCUSTOMER_SEGMENTCUSTOMER_TYPECUSTOMER_USER_IDDEEP_LINKDESCRIPTIONDESTINATION_ADESTINATION_BDESTINATION_LISTNEW_VERSIONOLD_VERSIONORDER_IDPARAM_01PARAM_02PARAM_03PARAM_04PARAM_05PARAM_06PARAM_07PARAM_08PARAM_09PARAM_10PAYMENT_INFO_AVAILABLEPREFERRED_NEIGHBORHOODSPRODUCT_IDPRODUCT_NAMEPURCHASE_CURRENCYRECEIPT_IDREGIONREGISTRATION_METHODREVIEW_TEXTSEARCH_STRINGSEGMENTSTATUSSUBSCRIPTION_IDSUCCESSSUGGESTED_DESTINATIONSSUGGESTED_HOTELSTUTORIAL_IDUTM_CAMPAIGNUTM_MEDIUMUTM_SOURCEVALIDATEDVERTICALVIRTUAL_CURRENCY_NAMEVOUCHER_CODE
PredefinedLong
AMOUNTDATE_ADATE_BDEPARTING_ARRIVAL_DATEDEPARTING_DEPARTURE_DATEHOTEL_SCORELEVELMAX_RATING_VALUENUM_ADULTSNUM_CHILDRENNUM_INFANTSPREFERRED_NUM_STOPSPREFERRED_STAR_RATINGSQUANTITYRATING_VALUERETURNING_ARRIVAL_DATERETURNING_DEPARTURE_DATESCORETRAVEL_STARTTRAVEL_ENDUSER_SCOREEVENT_STARTEVENT_END
PredefinedFloat
PREFERRED_PRICE_RANGEPRICEREVENUELATLONG
PredefinedObject
CONTENT
PredefinedListObject
CONTENT_LIST
PredefinedListString
CONTENT_IDS
Events buffering
Affise library will send any pending events with first opportunity, but if there is no network connection or device is disabled, events are kept locally for 7 days before deletion.
Push token tracking
To let affise track push token you need to receive it from your push service provider, and pass to Affise library. First add firebase integration to your app completing theese steps: Firebase Docs
After you have done with firebase inegration, add to your cloud messaging service onNewToken method Affise.share.addPushToken(token)
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(String(describing: fcmToken))")
// New token generated
Affise.share.addPushToken(pushToken: fcmToken)
}Reinstall Uninstall tracking
Affise automaticly track reinstall events by using silent-push technology, to make this feature work, pass push token when it is recreated by user and on you application starts up
Affise.share.addPushToken(pushToken: token)Deeplinks
To integrate deeplink support You can find out how to set up deeplinks in the official documentation.
Register deeplink callback right after Affise.share.init(..)
Affise.share.init(..)
Affise.shared.registerDeeplinkCallback { url in
let component = URLComponents(string: url.absoluteString)!
let screen = component.queryItems?.first(where: {$0.name == "screen"})?.value
if let screen = screen, screen == "special_offer" {
// open special offer activity
} else {
// open another activity
}
}Add deeplink handler to AppDelegate.swift
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey : Any] = [:]
) -> Bool {
Affise.shared.handleDeeplink(url: url)
return true
}Add key CFBundleURLTypes to Info.plist
Example: app/app/Info.plist
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>YOUR_AFFISE_APP_ID.affattr.com</string>
<key>CFBundleURLSchemes</key>
<array>
<string>affise</string>
</array>
</dict>
</array>Get random user Id
Use the next public method of SDK
Affise.shared.getRandomUserId()Get random device Id
Use the next public method of SDK
Affise.shared.getRandomDeviceId()WebView tracking
Initialize WebView
To integrate the library into the JavaScript environment, we added a bridge between JavaScript and the native SDK. Now you can send events and use the functionality of the native library directly from Webview. Here are step by step instructions:
// retreive WebView from view hierarhy
@IBOutlet weak var webView: WKWebView!
// make sure javascript is enabled
override func viewDidLoad() {
super.viewDidLoad()
webView.configuration.preferences.javaScriptEnabled = true
}
// initialize WebView with Affise native library
Affise.shared.registerWebView(webView: webView)
Other Javascript enviroment features is described below.
Events tracking JS
Demo app app/app/index.html
After WebView is initialized you send events from JavaScript enviroment
let data = { card: 4138, type: 'phone' };
let event = new AddPaymentInfoEvent({
userData: 'taxi',
};
event.addPredefinedParameter(PredefinedString.PURCHASE_CURRENCY, 'USD');
event.addPredefinedParameter(PredefinedFloat.PRICE, 2.19);
event.addPredefinedParameter(PredefinedObject.CONTENT, data);
Affise.sendEvent(event);Just like with native SDK, javascript enviroment also provides default events that can be passed from WebView:
AchieveLevelEventAddPaymentInfoEventAddToCartEventAddToWishlistEventClickAdvEventCompleteRegistrationEventCompleteStreamEventCompleteTrialEventCompleteTutorialEventContactEventContentItemsViewEventCustomId01EventCustomId02EventCustomId03EventCustomId04EventCustomId05EventCustomId06EventCustomId07EventCustomId08EventCustomId09EventCustomId10EventCustomizeProductEventDeepLinkedEventDonateEventFindLocationEventInitiateCheckoutEventInitiatePurchaseEventInitiateStreamEventInviteEventLastAttributedTouchEventLeadEventListViewEventLoginEventOpenedFromPushNotificationEventOrderEventOrderCancelEventOrderReturnRequestEventOrderReturnRequestCancelEventPurchaseEventRateEventReEngageEventReserveEventSalesEventScheduleEventSearchEventShareEventSpendCreditsEventStartRegistrationEventStartTrialEventStartTutorialEventSubmitApplicationEventSubscribeEventTravelBookingEventUnlockAchievementEventUnsubscribeEventUpdateEventViewAdvEventViewCartEventViewContentEventViewItemEventViewItemsEventInitialSubscriptionEventInitialTrialEventInitialOfferEventConvertedTrialEventConvertedOfferEventTrialInRetryEventOfferInRetryEventSubscriptionInRetryEventRenewedSubscriptionEventFailedSubscriptionFromRetryEventFailedOfferFromRetryEventFailedTrialFromRetryEventFailedSubscriptionEventFailedOfferiseEventFailedTrialEventReactivatedSubscriptionEventRenewedSubscriptionFromRetryEventConvertedOfferFromRetryEventConvertedTrialFromRetryEventUnsubscriptionEvent
Predefined event parameters JS
Each event can be extended with custom event parameters. By calling addPredefinedParameter function you can pass predefined parameters
For example:
let event = ...
event.addPredefinedParameter(PredefinedString.PURCHASE_CURRENCY, 'USD');
event.addPredefinedParameter(PredefinedFloat.PRICE, 2.19);
event.addPredefinedParameter(PredefinedLong.QUANTITY, 1);
event.addPredefinedParameter(PredefinedObject.CONTENT, { card: 4138, type: 'phone' });
event.addPredefinedParameter(PredefinedListObject.CONTENT_LIST, [{content:'songs'}, {content:'videos'}]);
Affise.sendEvent(event);Custom events JS
If above event functionality still limits your usecase, you can allways extend Event class to override fields you are missing
class MyCustomEvent extends Event {
constructor(args) {
super('MyCustom', args)
}
}Custom
ConversionId
Adds 3 PredefinedString values: PredefinedString.CONVERSION_ID, PredefinedString.ORDER_ID, PredefinedString.PRODUCT_ID
CONVERSION_ID=ORDER_ID_PRODUCT_ID
let event = AddToCartEvent()
let conversionId = event.customPredefined().conversionId("ORDER_ID", "PRODUCT_ID")
Affise.shared.sendEvent(event: event)