Code Samples

This page shows best practices of integrating Apphud SDK into your iOS project.

Main

Initialize Apphud SDK

Make sure you entered correct shared secret and added all subscription products in Apphud settings.

In your AppDelegate add just one line of code:

import ApphudSDK
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Apphud.start(apiKey: "APPHUD_API_KEY")
return true
}
}

Purchase Example

In your subscription purchase controller:

import ApphudSDK
class SubscriptionPurchaseController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
if Apphud.products() != nil {
reloadUI()
} else {
Apphud.refreshStoreKitProducts { products in
self.reloadUI()
}
}
}
func reloadUI(){
if let product = Apphud.product(productIdentifier: "YOUR_PRODUCT_ID") {
// set up pricing for this product
}
}
func purchaseProduct(product : SKProduct) {
Apphud.purchase(product) { result in
if let subscription = result.subscription, subscription.isActive(){
// has active subscription
} else if let purchase = result.nonRenewingPurchase, purchase.isActive(){
// has active non-renewing purchase
} else {
// handle error or check transaction status.
}
}
}
}

Restore Purchases

func restore(){
Apphud.restorePurchases { _, _, _ in
if Apphud.hasActiveSubscription() {
// success, dismiss purchase screen and unlock premium content
} else if Apphud.isNonRenewingPurchaseActive(productIdentifier: "producID"){
// has purchased non-renewing purchase, unlock content
} else {
// no active in-app purchases found
}
}
}

Set Up Push Notifications

Make sure Push Notifications are present in Signing & Capabilities tab in your project target.

In your AppDelegate add following:

import ApphudSDK
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Apphud.start(apiKey: APPHUD_API_KEY)
registerForPushNotifications()
return true
}
func registerForPushNotifications(){
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _,_ in}
UIApplication.shared.registerForRemoteNotifications()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Apphud.submitPushNotificationsToken(token: deviceToken, callback: {_ in})
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
Apphud.handlePushNotification(apsInfo: response.notification.request.content.userInfo)
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
Apphud.handlePushNotification(apsInfo: notification.request.content.userInfo)
completionHandler([])
}
}

Integrations

These examples below show how to add integrations with your analytics platform. You can easily add multiple integrations, they will not conflict.

Amplitude

In your AppDelegate add following:

import Amplitude_iOS
import ApphudSDK
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, ApphudDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Apphud.start(apiKey: "APPHUD_API_KEY")
Apphud.setDelegate(self)
Amplitude.instance()?.initializeApiKey("AMPLITUDE_KEY", userId: Apphud.userID())
return true
}
func apphudDidChangeUserID(_ userID: String) {
Amplitude.instance()?.setUserId(userID)
}
}

Mixpanel

In your AppDelegate add following:

import Mixpanel
import ApphudSDK
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, ApphudDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
#if DEBUG
let mixpanel_token = "TEST_MIXPANEL_TOKEN"
#else
let mixpanel_token = "LIVE_MIXPANEL_TOKEN"
#endif
Apphud.start(apiKey: "APPHUD_API_KEY")
Apphud.setDelegate(self)
Mixpanel.initialize(token: mixpanel_token)
Mixpanel.mainInstance().identify(distinctId: Apphud.userID())
return true
}
func apphudDidChangeUserID(_ userID: String) {
Mixpanel.mainInstance().identify(distinctId: Apphud.userID())
}
}

Apple Search Ads

In your AppDelegate add following:

import iAd
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Apphud.start(apiKey: "APPHUD_API_KEY")
ADClient.shared().requestAttributionDetails { (data, error) in
if let data = data {
Apphud.addAttribution(data: data, from: .appleSearchAds, callback: nil)
}
}
return true
}
}

AppsFlyer

In your AppDelegate add following:

import AppsFlyerLib
import ApphudSDK
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, AppsFlyerTrackerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Apphud.start(apiKey: "APPHUD_API_KEY")
AppsFlyerTracker.shared().appsFlyerDevKey = "APPSFLYER_DEV_KEY"
AppsFlyerTracker.shared().appleAppID = "APPLE_APP_ID"
AppsFlyerTracker.shared().delegate = self
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {
AppsFlyerTracker.shared().trackAppLaunch()
}
func onConversionDataSuccess(_ conversionInfo: [AnyHashable : Any]!) {
Apphud.addAttribution(data: conversionInfo, from: .appsFlyer, identifer: AppsFlyerTracker.shared()?.getAppsFlyerUID()) { _ in }
}
func onConversionDataFail(_ error: Error) {
Apphud.addAttribution(data: ["error" : error.localizedDescription], from: .appsFlyer, identifer: AppsFlyerTracker.shared().getAppsFlyerUID()) { _ in }
}
}

Adjust

In your AppDelegate add following:

import AppsFlyerLib
import Adjust
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Apphud.start(apiKey: "APPHUD_API_KEY")
//Adjust
let adjustConfig = ADJConfig(appToken: adjustKey, environment: ADJEnvironmentProduction) // or ADJEnvironmentSandbox
adjustConfig?.delegate = self
Adjust.appDidLaunch(adjustConfig)
return true
}
}
extension AppDelegate: AdjustDelegate {
func adjustAttributionChanged(_ attribution: ADJAttribution?) {
if let data = attribution?.dictionary() {
Apphud.addAttribution(data: data, from: .adjust) { (result) in }
} else if let adid = Adjust.adid() {
Apphud.addAttribution(data: ["adid" : adid], from: .adjust) { (result) in }
}
}
}

Branch

Make sure branch_key is added to your Info.plist with live and test keys.

import Branch
import ApphudSDK
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
#if DEBUG
Branch.setUseTestBranchKey(true)
#endif
Apphud.start(apiKey: "APPHUD_API_KEY")
Branch.getInstance()?.initSession(launchOptions: launchOptions, andRegisterDeepLinkHandler: {_, _ in })
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {
AppEvents.activateApp()
}
}

Facebook

In your AppDelegate add following:

import Branch
import ApphudSDK
import FBSDKCoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Initialize ApphudSDK
Apphud.start(apiKey: "APPHUD_API_KEY")
// Initialize Facebook
ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
// passing empty attribution data from Facebook to Apphud
Apphud.addAttribution(data: [:], from: .facebook, callback: nil)
return true
}
}

Objective-C Sample Code

This code shows Apphud SDK initialization with all integrations added. You can safely remove code related to integrations that you don't need.

#import <ApphudSDK-Swift.h>
#import <Branch/Branch.h>
#import <Mixpanel/Mixpanel.h>
#import <AppsFlyerLib/AppsFlyerTracker.h>
#import <Amplitude_iOS/Amplitude.h>
#import <Adjust/Adjust.h>
#import <iAd/iAd.h>
@interface AppDelegate () <UNUserNotificationCenterDelegate, ApphudDelegate, AppsFlyerTrackerDelegate, AdjustDelegate>
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[Apphud startWithApiKey:@"APPHUD_API_KEY" userID:nil];
[Apphud setDelegate:self];
[Amplitude.instance initializeApiKey:@"AMPLITUDE_API_KEY" userId:Apphud.userID];
[Mixpanel sharedInstanceWithToken:@"MIXPANEL_TOKEN"];
[Mixpanel.sharedInstance identify:Apphud.userID];
[AppsFlyerTracker sharedTracker].appsFlyerDevKey = @"APPSFLYER_DEV_KEY";
[AppsFlyerTracker sharedTracker].appleAppID = @"APPLE_APP_ID";
[AppsFlyerTracker sharedTracker].delegate = self;
[[Branch getInstance] initSessionWithLaunchOptions:launchOptions];
ADJConfig *config = [ADJConfig configWithAppToken:@"adjust_token" environment:ADJEnvironmentProduction];
config.delegate = self;
[Adjust appDidLaunch:config];
[[ADClient sharedClient] requestAttributionDetailsWithBlock:^(NSDictionary<NSString *,NSObject *> * _Nullable attributionDetails, NSError * _Nullable error) {
if (attributionDetails != nil) {
[Apphud addAttributionWithData:attributionDetails from:ApphudAttributionProviderAppleSearchAds identifer:nil callback:nil];
}
}];
return YES;
}
- (void)adjustAttributionChanged:(ADJAttribution *)attribution {
if ([attribution.dictionary isKindOfClass:[NSDictionary class]] && attribution.adid != nil) {
[Apphud addAttributionWithData:attribution.dictionary from:ApphudAttributionProviderAdjust identifer:nil callback:^(BOOL result) {
}];
} else if ([Adjust adid] != nil) {
[Apphud addAttributionWithData:@{@"adid" : [Adjust adid]} from:ApphudAttributionProviderAdjust identifer:nil callback:^(BOOL result) {
}];
}
}
- (void)onConversionDataSuccess:(NSDictionary *)conversionInfo{
[Apphud addAttributionWithData:conversionInfo from:ApphudAttributionProviderAppsFlyer identifer:AppsFlyerTracker.sharedTracker.getAppsFlyerUID callback:^(BOOL callback) {}];
}
- (void)onConversionDataFail:(NSError *)error{
[Apphud addAttributionWithData:@{@"error" : error.localizedDescription} from:ApphudAttributionProviderAppsFlyer identifer:[[AppsFlyerTracker sharedTracker] getAppsFlyerUID] callback:^(BOOL result){}];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[AppsFlyerTracker.sharedTracker trackAppLaunch];
}
- (void)apphudDidChangeUserID:(NSString *)userID {
[Amplitude.instance setUserId:userID];
[Mixpanel.sharedInstance identify:Apphud.userID];
}