iOS
This guide describes how to add and use Apphud SDK to your iOS app.

Requirements

Apphud SDK requires minimum iOS 11.2 and Xcode 10 and Swift version 5.0.

Installation

Apphud SDK can be installed via CocoaPods, Carthage, Swift Package Manager or manually.

Install via CocoaPods

Add the following line to your Podfile:
1
pod 'ApphudSDK'
Copied!
In Objective-C project make sure use_frameworks! is added in your Podfile.

Install via Carthage

Add the following line to your Cartfile:
1
github "apphud/ApphudSDK"
Copied!
And then run in the Terminal:
1
carthage update
Copied!

Install via Swift Package Manager

Add package dependency with the following URL:
1
https://github.com/apphud/ApphudSDK
Copied!

Manual Installation

Copy all files from ApphudSDK folder to your project from this link.

Kids Category

Latest Apphud SDK version doesn't use AdSupport framework and doesn't access IDFA so it is safe to use SDK for Kids Category apps.

Configure Apphud SDK

Integration process consists of following parts:

Initialise SDK

To initialise Apphud SDK you will need SDK Token. It is a unique identifier of your Apphud application. You can get it in your Apphud application settings under General tab.
Basic initialisation looks like this:
Swift
Objective-C
1
import ApphudSDK
2
3
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
4
5
Apphud.start(apiKey: "YOUR_API_KEY")
6
7
// the rest of your code
8
return true
9
}
Copied!
1
#import <ApphudSDK-Swift.h>
2
3
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
4
5
// set observerMode to YES if you are running SDK in Observer (Analytics) mode.
6
// set your custom userID or nil to let Apphud automatically generate User ID (recommended)
7
[Apphud startWithApiKey:@"YOUR_API_KEY" userID:@"CUSTOM_USER_ID_OR_NIL" observerMode:NO];
8
// the rest of your code
9
return YES;
10
}
Copied!

Initialisation Options

There are additional parameters, like setting your custom unique User ID or running the SDK in observer mode:
Swift
Objective-C
1
Apphud.start(apiKey: "API_KEY", userID: "CUSTOM_USER_ID", observerMode: true)
Copied!
1
[Apphud startWithApiKey:@"API_KEY" userID:@"CUSTOM_USER_ID" observerMode:NO];
Copied!
When observerMode is true, Apphud SDK will not finish transactions automatically and will only listen for purchases. If you handle payments by your own code, then set true. Otherwise, if you purchase products using Apphud.purchase(product){} method, then you should set observerMode parameter to false. Default value is false.
You can also initialise SDK with custom Device ID. This should be used if you plan to use logout / login features. This method can also be used for user uniqueness to be by your own User ID. You can safely pass the same identifier to Device ID and User ID:
1
Apphud.startManually(apiKey: "YOUR_API_KEY", userID: "SOME_USER_ID", deviceID: "SOME_USER_ID")
Copied!
More information regarding User ID uniqueness and User merging can be found here.
Log out method will clear all saved data and reset SDK to uninitialised state:
1
// log out:
2
Apphud.logout()
3
// then start Apphud SDK again:
4
Apphud.startManually(apiKey: "YOUR_API_KEY", userID: "ANOTHER_USER_ID", deviceID: "ANOTHER_USER_ID")
Copied!

Configure Push Notifications

Configuring push notifications is highly recommended in order to use Rules – a powerful feature that lets you increase your app revenue by automatically offering a discount to a user at the specified moment.

URL for App Store Server Notifications

Make sure you have correctly set up URL for App Store Server Notifications. It is required to detect cancellations and refunds in real-time. Read more here.

Handle In-App Purchases

If you have a live app and already implemented purchasing logic, it's not necessary to rewrite your purchase code with Apphud methods. Apphud SDK will still automatically track all purchases in your app.
Apphud SDK provides a set of methods to manage subscriptions and non-renewing purchases. All these methods can be used regardless of how you purchased the product (via Apphud SDK or your existing code).

Get Paywalls (version 2.3.0 or above)

To get a paywalls use:
First option - “paywalls” Returns paywalls with their SKProducts, if configured in Apphud Products Hub. Returns nil if StoreKit products are not yet fetched from the App Store. To get notified when paywalls are ready to use, use paywallsDidLoadCallback – when it’s called, paywalls are populated with their SKProducts.
Swift
1
var paywall: ApphudPaywall?
2
var products: [ApphudProduct]?
3
4
Apphud.paywalls.map { (paywalls) in
5
// retrieve current paywall with identifier
6
paywall = paywalls.first(where: { $0.identifier == "current_paywall_id" })
7
8
// retrieve the products [ApphudProduct] from current paywall
9
products = paywall?.products
10
}
11
Copied!
Second option - “paywallsDidLoadCallback” callback is called when paywalls are fully loaded with their StoreKit products. Callback is called immediately if paywalls are already loaded. It is safe to call this method multiple times – previous callback will not be overwritten, but will be added to array and once paywalls are loaded, all callbacks will be called.
Swift
1
var paywall: ApphudPaywall?
2
var products: [ApphudProduct]?
3
4
Apphud.paywallsDidLoadCallback { (paywalls) in
5
// retrieve current paywall with identifier
6
paywall = paywalls.first(where: { $0.identifier == "current_paywall_id" })
7
8
// retrieve the products [ApphudProduct] from current paywall
9
products = paywall?.products
10
}
11
Copied!
Paywall is an array of ApphudPaywall objects. ApphudPaywall contains the list of products [ApphudProducts] , paywall’s identifier, and several other properties. To show Products in your app you need to get a Paywall by its identifier.
Please NOTE:
    1.
    You have to use methods Apphud.paywallShown(paywall) and Apphud.paywallClosed(paywall) if you want to show these events in Apphud. We don't track them automatically.
    2.
    The methodApphud.getPaywalls()has been deprecated in 2.3.0

Get StoreKit Products

Please NOTE: the methodApphud.products()has been deprecated. Use Apphud.getPaywallsinstead.
Apphud automatically fetches SKProduct objects upon launch. Make sure products identifiers are added in Apphud products. To get your products call:
Swift
Objective-C
1
// returns nil, if products are not yet loaded from the App Store
2
Apphud.products()
Copied!
1
[Apphud products];
Copied!
Keep in mind that Apphud.products() array is nil at launch. It takes some time to fetch product identifiers from Apphud and later load SKProducts from StoreKit. To get notified when products are loaded, use any of the following:
    productsDidFetchCallback(_ callback: @escaping ([SKProduct]) -> Void) method.
    didFetchProductsNotification() notification method.
    apphudDidFetchStoreKitProducts(_ products: [SKProduct]) delegate method of ApphudDelegate.
You can use whatever method you want.
You can also force refresh products by calling refreshStoreKitProducts(_ callback: (([SKProduct]) -> Void)?) method. A new request will be sent to the App Store for fetching SKProducts even if initial request is still loading. So you should only use this method as a fallback in your UI. See Apphud.swift file for details.

Make a Purchase

To make a purchase call:
Swift
Objective-C
1
Apphud.purchase(product) { result in
2
if let subscription = result.subscription, subscription.isActive(){
3
// has active subscription
4
} else if let purchase = result.nonRenewingPurchase, purchase.isActive(){
5
// has active non-renewing purchase
6
} else {
7
// handle error or check transaction status.
8
}
9
}
Copied!
1
[Apphud purchase:product callback:^(ApphudPurchaseResult * result) {
2
if (result.subcription.isActive){
3
// has active subscription
4
} else if (result.nonRenewingPurchase.isActive){
5
// has active non-renewing purchase
6
} else {
7
// handle error or check transaction status
8
}
9
}];
Copied!
This method will return an ApphudPurchaseResult object, which contains subscription model with all info about your subscription. ApphudPurchaseResult may also contain transaction, error and nonRenewingPurchase objects in case user purchased non-renewing purchase. See ApphudPurchaseResult.swift and ApphudSubscription.swift files for details.
You can also read In-App Purchase Testing Tips.

Check Subscription Status

Swift
Objective-C
1
Apphud.hasActiveSubscription()
Copied!
1
[Apphud hasActiveSubscription];
Copied!
Returns true if user has active subscription. Use this method to determine whether to unlock premium functionality to the user.

Get Subscription Details

To get subscription object (which contains expiration date, autorenewal status, etc.) use the following method:
Swift
Objective-C
1
Apphud.subscription()
Copied!
1
[Apphud subscription];
Copied!
See ApphudSubscription.swift file for details.

Check Non-renewing Purchase Status

Use this method to check whether the user has purchased in-app purchase and it's not refunded. Returns false if was never purchased or is refunded.
Swift
Objective-C
1
Apphud.isNonRenewingPurchaseActive(productIdentifier: "productID")
Copied!
1
[Apphud isNonRenewingPurchaseActiveWithProductIdentifier:@"producID"];
Copied!

Get Non-renewing Purchase Details

To get non-renewing purchases, which contain purchase date, product identifier and cancellation date, use the following method:
Swift
Objective-C
1
Apphud.nonRenewingPurchases()
Copied!
1
[Apphud nonRenewingPurchases];
Copied!
It will return array of all non-renewing in-app purchases user has ever purchased. In-app purchases are sorted by purchase date.

Restore Purchases

If your app doesn't have a login system, which identifies a premium user by his credentials, then you need a "restore" mechanism. If you already have a "restore purchases" mechanism by calling SKPaymentQueue.default().restoreCompletedTransactions(), then you have nothing to worry about: Apphud SDK will automatically intercept and send the latest App Store Receipt to Apphud servers when your restoration is completed. However, better to call our restore method from SDK:
Swift
Objective-C
1
Apphud.restorePurchases{ subscriptions, purchases, error in
2
if Apphud.hasActiveSubscription(){
3
// has active subscription
4
} else {
5
// no active subscription found, check non-renewing purchases or error
6
}
7
}
Copied!
1
[Apphud restorePurchasesWithCallback:^(NSArray<ApphudSubscription *> * _Nullable subscriptions, NSArray *purchases, NSError * _Nullable error) {
2
if (Apphud.hasActiveSubscription){
3
// has active subscription
4
} else {
5
// no active subscription found, check non-renewing purchases or error
6
}
7
8
}];
Copied!
Basically it just sends App Store Receipt to Apphud and returns subscriptions (or nil, if subscriptions are never purchased), non-renewing purchases (or nil, if there are no any) and an optional error.

Handle Promoted In-App Purchases

Do not get confused with Promotional Offers! Promoted in-app purchases are the ones that appear in the App Store page.
If you have in-app purchases that can be purchased directly from the App Store, you should implement a logic to continue a payment in the app.
To continue an in-app purchase transaction initiated from the App Store page, please implement the following ApphudDelegate method:
Swift
Objective-C
1
func apphudShouldStartAppStoreDirectPurchase(_ product: SKProduct) -> ((ApphudPurchaseResult) -> Void) {
2
// manage your UI here, show a progress hud, etc.
3
let callback : ((ApphudPurchaseResult) -> Void) = { result in
4
// check the result, hide a progress hud, etc.
5
}
6
return callback
7
}
Copied!
1
- (void (^)(ApphudPurchaseResult * _Nonnull))apphudShouldStartAppStoreDirectPurchase:(SKProduct *)product {
2
// manage your UI here, show a progress hud, etc.
3
return ^(ApphudPurchaseResult * _Nonnull result) {
4
// check the result, hide a progress hud, etc.
5
};
6
}
Copied!
You must return a callback block which will be called when a payment is finished. If you don't implement this method or return nil then a payment will not start; you can also save the product and return nil to initiate a payment later by yourself. You can also read Apple documentation for details.

Migrate Existing Paying Users

If you already have a live app with paying users and you want Apphud to track their subscriptions and non-renewing purchases, you should import their App Store receipts into Apphud. Apphud SDK doesn't automatically submit App Store receipts of your existing paying users. Run this code at launch of your app:
Swift
1
// hasPurchases - is your own boolean value indicating that current user is paying user.
2
if hasPurchases {
3
Apphud.migratePurchasesIfNeeded {_, _, _ in}
4
}
5
Copied!

Match User IDs for integrations

Some integrations require you to match user ids between Apphud and corresponding integration. Please see documentation for your integration for details.

Testing Integrations in Sandbox

To test integrations, ensure that test credentials are provided and make a sandbox in-app purchase.
Starting iOS 14 you can reset your trial eligibility in iOS Settings > App Store
Apphud will send all subscription events of current user to your test analytics, if test credentials are set in integration settings.
Sandbox events will never be sent to your production integrations. If test credentials are not provided, sandbox events will not be sent anywhere.
You can also click on "Send Test Event" near the integration's "..." button. This feature is available only for some Integrations.

User Properties

Please follow this guide.

Other

User Eligibility for Introductory Offer

You can read more about eligibility testing here.
You can use Apphud to determine if user is eligible for introductory offer:
Swift
Objective-C
1
// Check eligibility for introductory offer
2
Apphud.checkEligibilityForIntroductoryOffer(product: myProduct) { result in
3
// handle result
4
}
5
6
// Check eligibility for multiple products at one call
7
Apphud.checkEligibilitiesForIntroductoryOffers(products: products) { resultDict in
8
// handle result
9
}
Copied!
1
// Check eligibility for introductory offer
2
[Apphud checkEligibilityForIntroductoryOfferWithProduct:myProduct callback:^(BOOL eligible) {
3
// handle result
4
}];
5
6
// Check eligibility for multiple products at one call
7
[Apphud checkEligibilitiesForIntroductoryOffersWithProducts:productsArray callback:^(NSDictionary * resultDict) {
8
// handle result
9
}];
Copied!

User Eligibility for Promotional Offer

You can read more about eligibility testing here.
You can also use Apphud to determine if user is eligible for promotional offer:
Swift
1
// Check eligibility for promotional offer
2
Apphud.checkEligibilityForPromotionalOffer(product: myProduct) { result in
3
// handle result
4
}
5
6
// Check eligibility for multiple products at one call
7
Apphud.checkEligibilitiesForPromotionalOffers(products: products) { resultDict in
8
// handle result
9
}
Copied!
Last modified 2mo ago