Git Product home page Git Product logo

matomo-sdk-ios's Introduction

MatomoTracker (former PiwikTracker) iOS SDK

The MatomoTracker is an iOS, tvOS and macOS SDK for sending app analytics to a Matomo server. MatomoTracker can be used from Swift and Objective-C.

Fancy help improve this SDK? Check this list to see what is left and can be improved.

Installation

The MatomoTracker can be installed via CocoaPods, Carthage and the Swift Package Manager. In every file you want to use the MatomoTracker, don't forget to import the framework with import MatomoTracker.

CocoaPods

Use the following in your Podfile.

pod 'MatomoTracker', '~> 7.5'

Then run pod install.

Carthage

Carthage is a non intrusive way to install MatomoTracker to your project. It makes no changes to your Xcode project and workspace. Add the following to your Cartfile:

github "matomo-org/matomo-sdk-ios"
Swift Package Manager

You can use the Swift Package Manager as integration method. If you want to use the Swift Package Manager as integration method, either use Xcode to add the package dependency or add the following dependency to your Package.swift:

.package(url: "https://github.com/matomo-org/matomo-sdk-ios.git", from: "v7.5"),

Usage

Matomo Instance

The Matomo iOS SDK doesn't provide a instance of the PiwikTracker. In order to be able to track data you have to create an instance first.

let matomoTracker = MatomoTracker(siteId: "23", baseURL: URL(string: "https://demo2.matomo.org/piwik.php")!)

The siteId is the ID that you can get if you add a website within the Matomo web interface. The baseURL it the URL to your Matomo web instance and has to include the "piwik.php" or "matomo.php" string.

You can either pass around this instance, or add an extension to the MatomoTracker class and add a shared instance property.

extension MatomoTracker {
    static let shared: MatomoTracker = MatomoTracker(siteId: "1", baseURL: URL(string: "https://example.com/piwik.php")!)
}

The siteId is the ID that you can get if you add a website within the Matomo web interface. The baseURL is the URL to your Matomo web instance and has to include the "piwik.php" or "matomo.php" string.

You can use multiple instances within one application.

Opting Out

The MatomoTracker SDK supports opting out of tracking. Please use the isOptedOut property of the MatomoTracker to define if the user opted out of tracking.

matomoTracker.isOptedOut = true

Tracking Page Views

The MatomoTracker can track hierarchical screen names, e.g. screen/settings/register. Use this to create a hierarchical and logical grouping of screen views in the Matomo web interface.

matomoTracker.track(view: ["path","to","your","page"])

You can also set the url of the page.

let url = URL(string: "https://matomo.org/get-involved/")
matomoTracker.track(view: ["community","get-involved"], url: url)

Tracking Events

Events can be used to track user interactions such as taps on a button. An event consists of four parts:

  • Category
  • Action
  • Name (optional, recommended)
  • Value (optional)
matomoTracker.track(eventWithCategory: "player", action: "slide", name: "volume", value: 35.1)

This will log that the user slid the volume slider on the player to 35.1%.

Tracking search

The MatomoTracker can track how users use your app internal search. You can track what keywords were searched for, what categories they use, the number of results for a certain search and what searches resulted in no results.

matomoTracker.trackSearch(query: "Best mobile tracking", category: "Technology", resultCount: 15)

Custom Dimension

The Matomo SDK currently supports Custom Dimensions for the Visit Scope. Using Custom Dimensions you can add properties to the whole visit, such as "Did the user finish the tutorial?", "Is the user a paying user?" or "Which version of the Application is being used?" and such. Before sending custom dimensions please make sure Custom Dimensions are properly installed and configured. You will need the ID of your configured Dimension.

After that you can set a new Dimension,

matomoTracker.set(value: "1.0.0-beta2", forIndex: 1)

or remove an already set dimension.

matomoTracker.remove(dimensionAtIndex: 1)

Dimensions in the Visit Scope will be sent along every Page View or Event. Custom Dimensions are not persisted by the SDK and have to be re-configured upon application startup.

Custom User ID

To add a custom User ID, simply set the value you'd like to use on the userId field of the tracker:

matomoTracker.userId = "coolUsername123"

All future events being tracked by the SDK will be associated with this userID, as opposed to the default UUID created for each Visitor.

Custom Visitor ID persisted on app starts

MatomoTracker will generate an _id upon first usage and will use this value to recognize the current visitor. This _id is persisted over app starts.

If you want to set your own visitor id, you can set your own visitor id with the forcedVisitorId field. Make sure you use a 16 character long hexadecimal string. The forcedVisitorId is persisted over app starts.

matomoTracker.forcedVisitorId = "0123456789abcdef"

Because the SDK persists this visitor id on app start, then we recommend to ask users for consent before tracking your app users.

Campaign Tracking

The Matomo iOS SDK supports campaign tracking.

matomoTracker.trackCampaign(name: "campaign_name", keyword: "campaign_keyword")

Content Tracking

The Matomo iOS SDK supports content tracking.

matomoTracker.trackContentImpression(name: "preview-liveaboard", piece: "Malaysia", target: "https://dummy.matomo.org/liveaboard/malaysia")
matomoTracker.trackContentInteraction(name: "preview-liveaboard", interaction: "tap", piece: "Malaysia", target: "https://dummy.matomo.org/liveaboard/malaysia")

Goal Tracking

The Matomo iOS SDK supports goal tracking.

matomoTracker.trackGoal(id: 1, revenue: 99.99)

Order Tracking

The Matomo iOS SDK supports order tracking.

let items = [
  OrderItem(sku: "product_sku_1", name: "iPhone Xs", category: "phone", price: 999.99, quantity: 1),
  OrderItem(sku: "product_sku_2", name: "iPhone Xs Max", category: "phone", price: 1199.99, quantity: 1)
]

matomoTracker.trackOrder(id: "order_id_1234", items: items, revenue: 2199.98, subTotal: 2000, tax: 190.98, shippingCost: 9)

Advanced Usage

Manual dispatching

The MatomoTracker will dispatch events every 30 seconds automatically. If you want to dispatch events manually, you can use the dispatch() function.

Session Management

The MatomoTracker starts a new session whenever the application starts. If you want to start a new session manually, you can use the startNewSession() function. You can, for example, start a new session whenever the user enters the application.

func applicationWillEnterForeground(_ application: UIApplication) {
  matomoTracker.startNewSession()
}

Logging

The MatomoTracker per default logs warning and error messages to the console. You can change the LogLevel.

matomoTracker.logger = DefaultLogger(minLevel: .verbose)
matomoTracker.logger = DefaultLogger(minLevel: .debug)
matomoTracker.logger = DefaultLogger(minLevel: .info)
matomoTracker.logger = DefaultLogger(minLevel: .warning)
matomoTracker.logger = DefaultLogger(minLevel: .error)

You can also write your own Logger and send the logs wherever you want. Just write a new class/struct and let it conform to the Logger protocol.

Custom User Agent

The MatomoTracker will create a default user agent derived from the WKWebView user agent. You can instantiate the MatomoTracker using your own user agent.

let matomoTracker = MatomoTracker(siteId: "5", baseURL: URL(string: "http://your.server.org/path-to-matomo/piwik.php")!, userAgent: "Your custom user agent")

Sending custom events

Instead of using the convenience functions for events and screen views for example you can create your event manually and even send custom tracking parameters. This feature isn't available from Objective-C.

func sendCustomEvent() {
  guard let matomoTracker = MatomoTracker.shared else { return }
  let downloadURL = URL(string: "https://builds.matomo.org/piwik.zip")!
  let event = Event(tracker: matomoTracker, action: ["menu", "custom tracking parameters"], url: downloadURL, customTrackingParameters: ["download": downloadURL.absoluteString])
  matomoTracker.track(event)
}

All custom events will be URL-encoded and dispatched along with the default Event parameters. Please read the Tracking API Documentation for more information on which parameters can be used.

Also: You cannot override Custom Parameter keys that are already defined by the Event itself. If you set those keys in the customTrackingParameters they will be discarded.

Automatic url generation

You can define the url property on every Event. If none is defined, the SDK will try to generate a url based on the contentBase of the MatomoTracker. If the contentBase is nil, no url will be generated. If the contentBase is set, it will append the actions of the event to it and use it as the url. Per default the contentBase is generated using the application bundle identifier. For example http://org.matomo.skd. This will not result in resolvable urls, but enables the backend to analyse and structure them.

Event dispatching

Whenever you track an event or a page view it is stored in memory first. In every dispatch run a batch of those events are sent to the server. If the device is offline or the server doesn't respond these events will be kept and resent at a later time. Events currently aren't stored on disk and will be lost if the application is terminated. #137

Contributing

Please read CONTRIBUTING.md for details.

License

MatomoTracker is available under the MIT license.

matomo-sdk-ios's People

Contributors

b123400 avatar briscula avatar brototyp avatar eligutovsky avatar elitalon avatar iltofa avatar iskander508 avatar janhalousek avatar jkrumow avatar julyyq avatar kanjanasi avatar krazzbeluh avatar manuroe avatar mattab avatar mattiaslevin avatar minitrue22 avatar misnikovroman avatar niksawtschuk avatar notjosh avatar nwhittaker avatar pe-te avatar phranck avatar sgiehl avatar sieren avatar simonnickel avatar soulchild avatar thomasgoehringer avatar thorstenstark avatar tobyhsu avatar tsteur avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

matomo-sdk-ios's Issues

Add support for Search feature

Many apps offer the user the possibility search for things (the search depends on domain context.

Add The Piwik REST API support tracking search requests.
"The Site Search keyword. When specified, the request will not be tracked as normal pageview but will instead be tracked as a “Site Search” request."
http://piwik.org/docs/tracking-api/reference/

Add a new method for tracking a search done within the app.
Parameters:
-word
-category (optional)
-hitCount (optional)

Support Content Tracking

This will be a new feature in Piwik 2.7.0 see matomo-org/matomo#4996 .

In PHP Tracker there are two new methods see https://github.com/piwik/piwik/blob/master/libs/PiwikTracker/PiwikTracker.php#L556-L583

doTrackContentImpression($contentName, $contentPiece = 'Unknown', $contentTarget = false)

It maps to the three parameters c_n, c_p and c_t see https://github.com/piwik/piwik/blob/master/libs/PiwikTracker/PiwikTracker.php#L894-L911

and

doTrackContentInteraction($interaction, $contentName, $contentPiece = 'Unknown', $contentTarget = false)

Which sends to the four parameters c_i, c_n, c_p and c_t see https://github.com/piwik/piwik/blob/master/libs/PiwikTracker/PiwikTracker.php#L914-L948

Content piece (c_p) and target (c_t) are both optional and should be only sent if a value is set. Content piece defaults to "Unknown" in the PHP implementation but a user could pass the boolean value false to not send any value or content piece.

Do you need more information?

Cocoapods update to 2.5.2

Hi, please update your cocoapods version to 2.5.2. As of today when installing PiwikTracker you get version 2.5.1. Thanks.

PiwikTracker retrieves events in wrong order

In the -[PiwikTracker eventsFromStore:completionBlock:] method, the fetch request is created like this:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"PTEventEntity"];

// Oldest first
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
fetchRequest.sortDescriptors = @[sortDescriptor];

To obtain the oldest events first, the sort descriptor should specify ascending:YES instead of ascending:NO. As-is, events are retrieved newest first, which can cause them to be displayed by Piwik out of-order.

Cannot create an NSPersistentStoreCoordinator with a nil model

When integrating this library into my app via Cocoapods, additional steps are needed in order for it to work, otherwise this message pops up and the app crashes.

I had to manually create piwiktracker.momd file with momc utility from Xcode, and include it in my app bundle. Is it possible to automate this process in further versions?

Expose visit scope customer variables

Expose a method to set visit scope variables.

Piwik documentation
http://piwik.org/docs/custom-variables/

Current the SDK sets the app name and version is set using custom variables. Allow the dev to turn this off in order to access all 5 custom variable slots. Should this be default on or off?

Investigation if the visit scope params can be sent in each tracking request for the same session of if we need to same the cookie generated by the Piwik server and send in subsequent requests (try to avoid the cookie).

startTracker crashes asking for main thread

This code invokes the following crash
[tracker startTrackerWithPiwikURL:PIWIK_URL
siteID:SITE_ID_TEST
authenticationToken:nil
withError:&error];

Console error is

Tried to obtain the web lock from a thread other than the main thread or the web thread.
This may be a result of calling to UIKit from a secondary thread. Crashing now...
1 WebThreadLock
2 -[UIWebView _webViewCommonInit:]
3 -[UIWebView initWithFrame:]
4 -[UIView init]
5 -[PTUserAgentReader userAgentStringWithCallbackBlock:]
6 -[PiwikTracker userAgent]
7 __44-[PiwikTracker dispatchWithCompletionBlock:]_block_invoke_0
8 _dispatch_call_block_and_release
9 _dispatch_queue_drain
10 _dispatch_queue_invoke
11 _dispatch_worker_thread2
12 _dispatch_worker_thread3
13 _pthread_wqthread
14 start_wqthread

Event emitted on new session creation

It would be useful to raise an event when a new session is started.
This could be subscribed to by the application and used to set session custom variables for example. This would resolve issues where session custom variables are set before the first event is raised, and hence deleted when the session is created.

How to use strategy?

Hi,

how would I use PTTimerDispatchStrategy?

I tried:

self.trackerStrategy =  [PTTimerDispatchStrategy strategyWithErrorBlock:^(NSError *error) {

}];
_trackerStrategy.timeInterval = 60;
[_trackerStrategy setStartDispatchTimer:YES];

But it didn't fire up?!

Thanks

Default prefixing to separate screen views, events and exceptions

Piwik only support reporting page views, goals and searches. These are not 100% applicable to the native app domain.

Use a prefixing schema and a set of naming rules to support:

Prefix page view reporting to Piwik depending on the type of event
-Screen views -> window
-Events -> event
-Exception -> exception
-Social interaction -> social

See example here
http://piwik.org/blog/2012/04/how-to-use-piwik-to-track-mobile-apps-activity-clicks-phones-errors-etc/

The prefixing should be default on. It should be possible to turn it off and use no or a customer prefixing.

The documentation should be update to explain this concept.

Custom timestamps in bulk requests?

Hello,

I've got two questions:

Question A) is my debugging correct, that piwik ios sdk currently doesn't support sending the timestamp of an action in an bulk request because the feature auth_token is removed?

I was wondering, why all events which were sent in a batch have the same timestamp shown in Piwik. It seems, that server_time in piwik is always set to the time the batch was received and not when the action was made on the device.

I have noticed, that there is some functionality for custom timestamps (cdt), but which only works with the auth_token (perhaps that hackers can't put bulk old requests to piwik and the owner of the piwik installation doesn't notice, that his data is being changed afterwards).

As the data shown/saved in the piwik dashboard now is not correct, I'm thinking about patching the piwik (php) installation to remove this requirement of the auth_token for timestamps not older than 2 days or using an old commit of piwik ios sdk, but I understand, that scraping the auth_token from the ios binary file isn't that difficult.

Question B) Do you have a idea for a solution to this issue?

Thank you and best regards,

Write a Google Analytics migration guide

Write a guide for how to migration from using Google Analytics tracker to the Piwik tracker.

Probably need to provide info for migrating both from GA v2 and v3 since there are major changes to the interface.

Bulk import API broken with Piwik 2.0?

I upgraded my Piwik server to version 2.0 today, and now attempts to use the bulk import API result in a 500 response from the server.

I'll try to get more details when I have time, but for now I am just forcing the number of events per request to be 1 so that the non-bulk API is used.

Improve unique generation of userID

There is only 16 characters available for sending the unique user id. This is not enough to ensure to fit the UDID.

Create a better algorithm to shrink the UDID into the 16 chars. Also report this limitation with Piwik team at a ticker and recommend that the length is increased.

Change threading model

Do not run code in a separate thread, only the network request needs to be asynchronous.
Core data operations should run on the main thread normally

Support OSX

The frameworks should support OSX and iOS.

Need to remove some dependencies to UIWebView (used to figure out the user-agent).
Should not easy after shifting to AF networking.

/Mattias

Update iOS demo project

Update the demo project to contain examples of all/most of the features available in the API.

Error in Sample code in wiki

- (void)viewDidAppear:(BOOL)animated {
  // Track screen views in your view controllers
  // Recommendation: track the full hierarchy of the screen, e.g. screen/view1/view2/currentView
  [[PiwikTracker sharedInstance] sendViews:@"view1", @"view2", self.title];
}

sendViews: is missing a nil as last parameter

Remove auth_token from the SDK (should no longer be used)

As on Piwik 2.8 the auth_token is no longer needed for the Piwik server to accept (some) parameters.

Remove all references to the auth_token from the code and documentation due to security reasons. Write a short section what it is removed and how to migrate.

This change will break the API (a little).

License

Hi,

I'd like to use it in my project, could you please provide a license (like MIT)?

Thanks and best regards,
Tom

Restructure workspace and project

Restructure workspace and project

Piwik (workspace)
  PiwikTracker (folder)
    source code
  PiwikiOSDemo (project with an iOS build target)
    demo source code
  PiwikOXDemo (project with and OSX build target
    demo source code
  Pods (pod dependency targets)

Look at the AFNetworking organisation.

Need different demo project and/or test project for iOS and OSX

AFNetworking build issue

I integrated the SDK via CocoaPods into my project and when I build with iOS8 SDK I get this error:

Cannot find interface declaration for 'AFHTTPClient', superclass of 'PiwikTracker'

Although AFHTTPClient points to the correct file when resolved in Xcode. My project itself doesn't use AFNetworking.

Update: Removed any imports and usage of PiwikTracker.h - build runs fine.
However, as soon as I import the Header file or the Library <PiwikTracker/PiwikTracker.h> I get the same Error again.

Update: So, it took me quite some time, but I finally fixed it by changing the #import AFNetworking.h in PiwikTracker.h to #import "AFHTTPClient.h".

Update the API description

Add more description and discussion to methods.
Add class descriptions.

Generate and upload new API description to Github (create a target in Xcode that does this).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.