Skip to content

Usage (iOS)

To use the SDK, you have to call the respective API.

Demo Application

A demo content view is attached to the SDK in SurfmeterAnalyticsContentView.swift. You can use this as a reference implementation for your own application.

Basic Example

In the simplest case, you need a builder for the API and attach it to your AVPlayer instance:

import AVFoundation
import AVPlayerAnalytics

let player = AVPlayer(url: URL(string: "https://example.com/manifest.mpd")!)
let builder = try SurfmeterAnalyticsBuilder(
    player: player!,
    apiKey: "your-api-key",
).setService(service: "your-service")
analytics = builder.build()
player.play()

Advanced Usage

With Custom Metadata

You can attach custom metadata to your analytics data in the builder:

let builder = try SurfmeterAnalyticsBuilder(
    player: player!,
    apiKey: "your-api-key",
)
    .setService(service: "your-service")
    .setMetadata(metadata: ["userId": "1234567890"])

These can be retrieved in the dashboard, and are very useful for segmenting your data for analysis purposes.

Note

Please make sure that if you send personal data such as customer IDs, names, or email addresses, you have the necessary consent of the user to do so.

Analytics Listener

You can implement the SurfmeterAnalyticsListener protocol to receive callbacks about the analytics state:

class SurfmeterAnalyticsListenerImpl: SurfmeterAnalyticsListener {
    func onSendingData() {
        print("Sending data")
    }

    func onError(_ error: String) {
        print("Error: \(error)")
    }

    func onStateChanged(_ state: AVPlayerAnalytics.AnalyticsState) {
        print("State changed: \(state)")
    }

    func onLog(level: AVPlayerAnalytics.LogLevel, tag: String, log: String) {
        // if you want more logs:
        // print("Log: \(level) \(tag) \(log)")
    }
}

Configuration with Listener

Here's how to set up the analytics with a listener and additional configuration:

let listener = SurfmeterAnalyticsListenerImpl()
let builder = try SurfmeterAnalyticsBuilder(
    player: player!,
    apiKey: "your-api-key"
)
.setService(service: "your-service")
.setEndpoint(endpoint: "your-api-endpoint")  // optional: custom endpoint
.setAnalyticsListener(listener: listener)

analytics = builder.build()

Managing Multiple Videos

When switching between videos, make sure to properly manage the analytics lifecycle:

// Finish current analytics session
analytics?.finish()

// Setup new video
let newVideoUrl = URL(string: "https://example.com/manifest2.mpd")!
player.replaceCurrentItem(with: AVPlayerItem(url: newVideoUrl))

// Initialize new analytics session
analytics = try builder.build()
player.play()

Error Handling

On an error, call the abort() method:

analytics.abort()

API Docs

Please refer to the documentation in docs/client_analytics for more details on the API.