Using Piwik PRO SDK
Tracking is centered on PiwikTracker. Configure it once at startup, then call PiwikTracker.sharedInstance() from your app. See Getting started.
Data anonymization
Anonymization lets you respect visitor consent while still collecting aggregated analytics data.
When isAnonymizationEnabled is true (the default), the SDK doesn’t collect the user ID. The SDK also generates a new visitor ID each time the app starts, when the ID is first needed.
Turn off anonymization only when your privacy policy allows identified tracking.
PiwikTracker.sharedInstance()?.isAnonymizationEnabled = false[PiwikTracker sharedInstance].isAnonymizationEnabled = NO;Tracking screen views
Requires Analytics
During a valid session you can track screen views. The SDK turns the screen name, or hierarchy, into a synthetic URL for the collector. By default, it prefixes screen segment. To turn this off, set isPrefixingEnabled = false. See isPrefixingEnabled.
Single screen:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
PiwikTracker.sharedInstance()?.sendView(view: "your_screen_path")
}- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[PiwikTracker sharedInstance] sendView:@"your_screen_path"];
}- view (required)
Logical screen name or path segment.
Hierarchical path in one event, from parent to child:
PiwikTracker.sharedInstance()?.sendViews(views: ["parent", "child"])[[PiwikTracker sharedInstance] sendViews:@[@"parent", @"child"]];When you build the UI with View and .onAppear, follow the patterns in Advanced usage: Using the SDK with SwiftUI.
Tracking custom events
Requires Analytics
Use sendEvent(category:action:name:value:path:) for taps, gestures, gameplay actions, and other interactions.
PiwikTracker.sharedInstance()?.sendEvent(
category: "category",
action: "action",
name: "label",
value: 1000,
path: "main/actionScreen"
)[[PiwikTracker sharedInstance]
sendEventWithCategory:@"category"
action:@"action"
name:@"label"
value:@1000
path:@"main/actionScreen"];category(required): Groups the event, such as gestures or feature areas.action(required): Specific action inside the category.name(optional): Label, such as which control was used.value(optional): Numeric value.path(optional): Path segment for the synthetic URL. When omitted, the SDK reuses the last generated page URL. SeesendEvent. Read more: custom events overview, event tracking guide.
Tracking exceptions
Requires Analytics
Use sendException(description:) to track handled errors in Analytics. The event category is Exception.
This method isn’t a full crash reporter.
do {
// work
} catch {
PiwikTracker.sharedInstance()?.sendException(description: "Content download error")
}[[PiwikTracker sharedInstance] sendExceptionWithDescription:@"Content download error"];description(required)
Short text. The SDK truncates it to 50 characters.
Tracking social interactions
Requires Analytics
PiwikTracker.sharedInstance()?.sendSocialInteraction(action: "like", network: "Facebook")[[PiwikTracker sharedInstance] sendSocialInteractionWithAction:@"like" network:@"Facebook"];- action (required)
Interaction type. Example: like, share. Read more:sendSocialInteraction). - network (required)
Social product name. Example: Facebook, Instagram.
Tracking deep links and campaigns
Requires Analytics
Measure campaigns built with the Campaign URL Builder. Pass the full URL, including the query string, to sendCampaign(url:).
Campaign parameters attach to the next analytics event, then clear.
PiwikTracker.sharedInstance()?.sendCampaign(
url: "https://www.example.com?pk_campaign=Email-SummerDeals&pk_keyword=LearnMore"
)[[PiwikTracker sharedInstance]
sendCampaign:@"https://www.example.com?pk_campaign=Email-SummerDeals&pk_keyword=LearnMore"];For deep links and pk_vid used in cross-device visitor ID tracking, see cross-platform tracking and setVisitorIdFrom.
Tracking downloads
Requires Analytics
PiwikTracker.sharedInstance()?.sendDownload(url: "https://your.server.com/bonusmap.zip")[[PiwikTracker sharedInstance] sendDownload:@"https://your.server.com/bonusmap.zip"];- url (required)
Resource the user downloads through your app.
Tracking application installs
Requires Analytics
Use applicationInstall() to track app installations. It runs at most onnce per installation. The older sendApplicationDownload() is deprecated. It runs at most once per app version.
PiwikTracker.sharedInstance()?.applicationInstall()[[PiwikTracker sharedInstance] applicationInstall];Returns true if a new install event was queued and false if this install was already tracked. See applicationInstall().
Call this method immediately after configuring the tracker. To track app updates, call applicationUpdate() during app startup.
Tracking outlinks
Requires Analytics
PiwikTracker.sharedInstance()?.sendOutlink(url: "https://partner.example/path")[[PiwikTracker sharedInstance] sendOutlink:@"https://partner.example/path"];- url (required)
The destination opened from your app.
Tracking search operations
Requires Analytics
PiwikTracker.sharedInstance()?.sendSearch(
keyword: "Space",
category: "Movies",
numberOfHits: 3
)[[PiwikTracker sharedInstance]
sendSearchWithKeyword:@"Space"
category:@"Movies"
numberOfHits:@3];- keyword (required)
- category (optional)
- numberOfHits (optional)
The number of results shown. The SDK includes the hit count only when the value is zero or greater. SeesendSearch.
Tracking content impressions and interactions
Requires Analytics
Impression:
PiwikTracker.sharedInstance()?.sendContentImpression(
name: "iOS content impression",
piece: "banner",
target: "https://www.example.com/",
url: nil
)[[PiwikTracker sharedInstance]
sendContentImpressionWithName:@"iOS content impression"
piece:@"banner"
target:@"https://www.example.com/"
url:nil];Interaction (e.g. tap):
PiwikTracker.sharedInstance()?.sendContentInteraction(
name: "iOS content impression",
interaction: "click",
piece: "banner",
target: "https://www.example.com/"
)[[PiwikTracker sharedInstance]
sendContentInteractionWithName:@"iOS content impression"
interaction:@"click"
piece:@"banner"
target:@"https://www.example.com/"];- name (required)
The name of the tracked content. - interaction (required)
The type of interaction with the content, for example, a click, tap. - piece / target (optional)
Additional information about the content or interaction.
Tracking goals
Requires Analytics
Call sendGoal(ID:revenue:) to track manual conversions. You can also provide an optional currencyCode.
If you've configured goals with automatic rules in Analytics, you may not need to call this method. What is a goal?
PiwikTracker.sharedInstance()?.sendGoal(ID: "27ecc5e3-8ae0-40c3-964b-5bd8ee3da059", revenue: 20)[[PiwikTracker sharedInstance] sendGoalWithID:@"27ecc5e3-8ae0-40c3-964b-5bd8ee3da059" revenue:@20];Tracking ecommerce (V2)
Use EcommerceProducts and Product (or addProductWithSku:... helper methods) with the V2 methods below.
The product fields are described in detail on each method page. In summary:
sku(required)
The product SKU.name(optional)
The product name.category(optional)
A string or an array of up to 5 category values.price(optional)
The product price.quantity(optional)
The product quantity.brand(optional)
The product brand.variant(optional)
The product variant.customDimensions(optional)
Product-level custom dimensions.
Product detail view
ecommerceProductDetailView(products:)
let products = EcommerceProducts()
products.addProduct(
sku: "craft-311",
name: "Unicorn Iron on Patch",
category: ["Crafts & Sewing", "Toys"],
price: "49.90",
quantity: 3,
brand: "DMZ",
variant: "blue",
customDimensions: [1: "coupon-2020", 2: "20%"]
)
PiwikTracker.sharedInstance()?.ecommerceProductDetailView(products: products)Add to cart
PiwikTracker.sharedInstance()?.ecommerceAddToCart(products: products)Remove from cart
ecommerceRemoveFromCart(products:)
PiwikTracker.sharedInstance()?.ecommerceRemoveFromCart(products: products)Cart update
ecommerceCartUpdate(products:grandTotal:)
PiwikTracker.sharedInstance()?.ecommerceCartUpdate(products: products, grandTotal: "149.70")Order (conversion)
ecommerceOrder(products:orderId:grandTotal:subTotal:tax:shipping:discount:)
PiwikTracker.sharedInstance()?.ecommerceOrder(
products: products,
orderId: "order-3415",
grandTotal: "231.30",
subTotal: "149.70",
tax: "39.60",
shipping: "60.00",
discount: "18.00"
)[[PiwikTracker sharedInstance] ecommerceOrder:products
orderId:@"order-3415"
grandTotal:@"231.30"
subTotal:@"149.70"
tax:@"39.60"
shipping:@"60.00"
discount:@"18.00"];Build products with EcommerceProducts.addProduct(sku:...) (as below), Product.productWithSku(...) + add(product:), or addProductWithSku:.... All are documented on ecommerceOrder() and sibling pages.
Tracking ecommerce transactions (legacy)
Requires Analytics
Deprecated: prefer ecommerce V2 above (
ecommerceOrder, cart actions, etc.).sendTransaction(transaction:)/PiwikTransactionremain only for legacy integrations.
Tracking custom variables
The feature is deprecated; use custom dimensions for new work.
Requires Analytics
setCustomVariable(index:name:value:scope:) supports .visit and .action scopes. With includeDefaultCustomVariable on (default), do not use visit indexes 1-3 for your own variables; use > 3 for visit scope, or any ≥ 1 for action scope; see the method page and Advanced usage.
PiwikTracker.sharedInstance()?.setCustomVariable(
index: 4,
name: "User type",
value: "subscriber",
scope: .visit
)[[PiwikTracker sharedInstance] setCustomVariableForIndex:4
name:@"User type"
value:@"subscriber"
scope:CustomVariableScopeVisit];Tracking custom dimensions
Requires Analytics
Set dimensions before the hit that should carry them using setCustomDimension(identifier:value:). identifier is the dimension ID from Piwik PRO (integer ≥ 1).
PiwikTracker.sharedInstance()?.setCustomDimension(identifier: 1, value: "visit")
PiwikTracker.sharedInstance()?.setCustomDimension(identifier: 2, value: "dashboard")
PiwikTracker.sharedInstance()?.sendView(view: "Home screen")[[PiwikTracker sharedInstance] setCustomDimensionForID:1 value:@"visit"];
[[PiwikTracker sharedInstance] setCustomDimensionForID:2 value:@"dashboard"];
[[PiwikTracker sharedInstance] sendView:@"Home screen"];After dimensions are attached to a request, the SDK clears them. Set them again before each tracking call that should include them (method notes).
Tracking user profile attributes
Requires Data Activation
Data Activation stores user profiles with data from a variety of sources. One of them can be a mobile application. You can create or update attributes of the user profile with the sendProfileAttributes method. Predefined attributes use the analytics. prefix, for example analytics.revenue. Custom attributes must first be defined with an event data key in Data Activation. See how to import data to custom attributes.
PiwikTracker.sharedInstance()?.sendProfileAttributes([
"analytics.revenue": 500,
"favorite_color": "green",
"vip": true,
"contract_end": Date()
])[[PiwikTracker sharedInstance] sendProfileAttributes:@{
@"analytics.revenue": @500,
@"favorite_color": @"green",
@"vip": @YES,
@"contract_end": [NSDate date]
}];-
An
attributesdictionary (required) – A dictionary of attribute names and values sent in one request. For custom attributes, use the event data key defined in Data Activation, not the attribute name returned bygetProfileAttributes(). -
Values can be
NSString,NSNumber(including booleans) orNSDate. Dates are sent in the ISO 8601 format in UTC, e.g.2023-07-21T17:32:28Z. IP addresses are passed asNSString. -
The method returns
trueif the attributes were queued for sending andfalseotherwise.
The profile is identified by the visitor ID and the user ID, if it is set. The user ID is not sent when anonymization is enabled. Attributes are queued and dispatched together with analytics events, so they are not lost without a network connection. Requests rejected by Data Activation, for example with an unknown attribute or a disabled module, are not retried. Data Activation processes attributes asynchronously, so new values may not be available immediately.
Reading user profile attributes
Requires Data Activation
It is possible to read only the profile attributes enabled for public access in Data Activation. To get user profile attributes use the getProfileAttributes method:
PiwikTracker.sharedInstance()?.getProfileAttributes { profileAttributes, error in
// handle result or error
}[[PiwikTracker sharedInstance] getProfileAttributesWithCompletionBlock:^(NSDictionary<NSString *, id> * _Nullable profileAttributes, NSError * _Nullable error) {
// handle result or error
}];- A completion block (required) - called with the dictionary of attribute names and values, or with an error. Values are
NSString,NSNumber(including booleans) orNSArray.
Reading user audiences
Requires Data Activation
Data Activation audiences group users based on analytics data and profile attributes. To get IDs of the audiences the user belongs to use the getAudiences method:
PiwikTracker.sharedInstance()?.getAudiences { audienceIDs, error in
// handle result or error
}[[PiwikTracker sharedInstance] getAudiencesWithCompletionBlock:^(NSArray<NSString *> * _Nullable audienceIDs, NSError * _Nullable error) {
// handle result or error
}];- A completion block (required) - called with the list of audience IDs, empty if the user does not belong to any audience, or with an error, e.g.
HTTP 404: ...when the profile does not exist yet.
Checking audience membership
Requires Data Activation
You can check if the user belongs to a given audience, for example, to show a special offer. To check it, use the isUserInAudience method:
PiwikTracker.sharedInstance()?.isUserInAudience(audienceID: audienceID) { isMember, error in
// handle result or error
}[[PiwikTracker sharedInstance] isUserInAudienceWithID:audienceID completionBlock:^(BOOL isMember, NSError * _Nullable error) {
// handle result or error
}];- An audienceID (required) - ID of the audience. You can find it in Data Activation > Audiences.
- A completion block (required) - called with
trueif the user belongs to the audience,falseif not, or with an error.
Data Activation identifies the user by the visitor ID, so you need to disable anonymization with isAnonymizationEnabled = false. Otherwise, the SDK generates a new visitor ID each time the app starts and may not find the existing profile.
On iOS, this setting isn't saved between application launches, so set it each time the tracker starts. Completion blocks are called asynchronously on the main thread. In opt out mode, the SDK doesn't send the request and calls the completion block with an error.
Migrating from Audience Manager
Audience Manager is no longer available, and its methods have been removed from the SDK. Use Data Activation methods instead:
| Removed | Replacement |
|---|---|
checkMembership(withAudienceID:completionBlock:) | isUserInAudience(audienceID:completion:) |
audienceManagerGetProfileAttributes(_:) | getProfileAttributes(completion:) |
sendAudienceManagerAttribute(name:value:) | sendProfileAttributes(_:) |
userEmail | No replacement, use userID to identify the user |
deviceID | No replacement |
If you use a custom PiwikDispatcher, you can remove the following Audience Manager methods from it. The SDK no longer calls them:
sendAudienceManagerEvents:success:failure:checkAudienceMembershipWithVisitorID:websiteID:audienceID:success:failure:audienceManagerGetUserProfileAttributes:websiteID:success:failure:
To use Data Activation with a custom PiwikDispatcher, implement its optional Data Activation methods.
Audience Manager events saved by previous SDK versions and not sent yet are deleted.
Full API reference
Every signature, parameter table and edge case lives in the Methods index and linked pages.
Updated 14 days ago