← Metriku

Documentation

Swift / SwiftUI. App Key → SDK → optional APNs + Firebase → push, live config, and the console. iOS SDK v1.7.1 · Changelog.

How are you integrating?

AI copy-paste prompts

Paste into Cursor / Claude / ChatGPT with your App Key and Bundle ID filled in. Pin SPM to latest 1.7.1. Prefer Project setup → Setup iOS → I’m implementing with AI for a copy that already includes your real App Key and Bundle ID.

A · Full iOS integration (recommended)

Integrate Metriku analytics + messaging into this iOS app end-to-end.

## Detect UI framework
- If the app is UIKit / AppDelegate → use UIKit wiring below.
- If the app is SwiftUI (@main App) → use SwiftUI wiring (+ UIApplicationDelegateAdaptor for push token).
- Do not mix styles incorrectly; follow the project’s existing entry point.

## Package (SPM) — pick ONE
- Closed-source binary (recommended for App Store apps):
  https://github.com/haxhiuurim/Metriku.git  → from: 1.7.1
  Product: Metriku  ·  import MetrikuSDK
- Open source (debugging / contributing):
  https://github.com/haxhiuurim/iOSMetriku.git
  Same product/import names.

Docs: https://metriku.dev/docs/ios
Console: https://metriku.dev/dashboard
Changelog: https://metriku.dev/changelog (latest 1.7.1)

## Credentials (fill these)
- App Key: YOUR_APP_KEY
- Package / Bundle ID: YOUR.BUNDLE.ID  (must match Xcode + the Metriku project package ID)
- API host is FIXED: https://metriku.dev  (do NOT add a custom base URL)

## Bootstrap (UIKit)
1. import MetrikuSDK
2. #if DEBUG  Metriku.setSandbox(true)  #endif
3. Metriku.initialize("YOUR_APP_KEY", launchOptions: launchOptions)
4. Enable Push Notifications + Background Modes → Remote notifications
5. didRegisterForRemoteNotificationsWithDeviceToken → Metriku.Notifications.setPushToken(deviceToken)
6. Metriku.Notifications.requestPermission { _ in }
7. Forward taps: Metriku.Notifications.handleNotificationResponse(response)
8. Metriku.User.printDebugIdentity()

## Bootstrap (SwiftUI)
1. @main App.init → Metriku.setSandbox (DEBUG) + Metriku.initialize("YOUR_APP_KEY", launchOptions: nil)
2. @UIApplicationDelegateAdaptor for didRegisterForRemoteNotificationsWithDeviceToken → setPushToken
3. .onAppear { Metriku.Notifications.requestPermission { _ in } }
4. Forward taps: Metriku.Notifications.handleNotificationResponse(response)
5. Metriku.User.printDebugIdentity()

## Push — Notification Service Extension (REQUIRED when using push / rich images)
Metriku sends mutable-content pushes. Add an iOS Notification Service Extension target so
received notifications display with title/body/media correctly:
1. Xcode → File → New → Target → Notification Service Extension (e.g. MetrikuNSE)
2. SPM: add product MetrikuNotificationService to that extension target (same Metriku package)
3. In NotificationService.swift:

```swift
import UserNotifications
import MetrikuNotificationService

class NotificationService: UNNotificationServiceExtension {
  var contentHandler: ((UNNotificationContent) -> Void)?
  var bestAttemptContent: UNMutableNotificationContent?

  override func didReceive(
    _ request: UNNotificationRequest,
    withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
  ) {
    self.contentHandler = contentHandler
    bestAttemptContent = MetrikuNotificationService.didReceive(
      request,
      contentHandler: contentHandler
    )
  }

  override func serviceExtensionTimeWillExpire() {
    if let contentHandler, let bestAttemptContent {
      contentHandler(bestAttemptContent)
    }
  }
}
```

4. App Groups / entitlements: match your main app Bundle ID + Push capability as needed.
Without the NSE, rich images / media will not attach; still wire setPushToken + permission.

## Default attributes (ALWAYS add after initialize)
let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "?"
Metriku.User.setAttributes([
  "app_version": appVersion,
  "ios_version": UIDevice.current.systemVersion,
  "device_model": UIDevice.current.model,
  "platform": "ios",
])
// Also set any product attributes you already know (plan, locale, etc.)

## Identity
- If the app uses RevenueCat (SDK ≥ 1.7.1 preferred):
  Metriku.revenueCatIdentitySync = { id in
    if let id { Purchases.shared.logIn(id) { _, _, _ in } }
    else { Purchases.shared.logOut { _, _ in } }
  }
  Then Metriku.login(sameStringAsRevenueCat.appUserID) after auth (MUST match RC app_user_id).
  Or call Metriku.login(Purchases.shared.appUserID) after Purchases.logIn if you skip the hook.
- Metriku.logout() on sign-out

## Do NOT add location / geofencing (removed in SDK 1.5.0)
- There is NO Metriku.Location API
- Do NOT call Metriku.Location.startMonitoring / requestPermission / syncLocation
- Do NOT add NSLocationWhenInUseUsageDescription (or Always) for Metriku
- Do NOT enable Background Modes → Location for Metriku

## Analytics — instrument the WHOLE app (required)
Cover every meaningful surface — do not leave screens/buttons dark:
1) SCREENS: call Metriku.Analytics.screen("ScreenName") on every screen appear
   (UIKit: viewDidAppear / SwiftUI: .onAppear). Use stable human names (Home, Paywall, Settings…).
2) BUTTONS / CTAs: Metriku.Analytics.trackButton("button_id", screen: "ScreenName") on taps
   (primary CTAs, paywall buy, dismiss, settings toggles that matter).
3) PRODUCT EVENTS: Metriku.Analytics.track("event_name", properties: […]) for feature usage,
   onboarding steps, exports, search, errors the business cares about.
4) Optional Metriku.Analytics.flush() — usually unnecessary (auto debounce).

## Product flows — OPTIONAL (multi-step journeys, non-revenue)
Use Metriku.Flow when you want step-by-step conversion (start → steps → complete/quit).
Appears under Dashboard → Flows (not subscription Funnels).
Pass optional value when the user picks a choice on a step. Dashboard → Flows renders those choices as branch nodes in the step funnel (same visual model as the sales Funnel). Steps without values stay a single spine. Flow details still list per-step value breakdowns.
Screen appear → step("screen_name") with no value. Button / exclusive choice on that screen → same step name + value (e.g. cancel, keep_premium, dismiss). New screen after a choice → new step name; choices again via value. Abandon → quit(at: current step); success → complete.
Example (branching cancel / manage subscription):
  Metriku.Flow.start("manage_subscription")
  Metriku.Flow.step("manage_subscription", step: "access_active")
  // Choice on this screen → branch in Flows funnel:
  Metriku.Flow.step("manage_subscription", step: "access_active", value: "cancel")
  // or value: "keep_premium" / "dismiss"
  Metriku.Flow.step("manage_subscription", step: "cancel_reasons")
  Metriku.Flow.step("manage_subscription", step: "cancel_reasons", value: "too_expensive")
  Metriku.Flow.step("manage_subscription", step: "winback")
  Metriku.Flow.step("manage_subscription", step: "winback", value: "try_offer")
  Metriku.Flow.complete("manage_subscription")
  // or Metriku.Flow.quit("manage_subscription", at: "access_active", value: "dismiss")
Skip this section if the app has no multi-step product journeys to measure.

## Subscription funnel — pick ONE path (never both)
A) App HAS RevenueCat (+ Metriku webhook configured) — APP CALLS:
  1. Install Metriku.revenueCatIdentitySync (SDK ≥ 1.7.1) so login/logout keep RC appUserID in sync
  2. Metriku.login(sameStringAsRevenueCat.appUserID)
  3. Metriku.Analytics.trackPaywallView() when the paywall UI is shown
  DO NOT call trackTrialStarted / trackTrialConverted / trackPurchaseCompleted /
    trackRenewed / trackCanceled / trackBillingGraceFailed
  Webhook URL: Metriku → App Settings → RevenueCat webhooks → Copy URL
  Auth in RevenueCat MUST include BOTH:
    1) Authorization header = Bearer token from Metriku (Generate & save)
    2) HMAC signing secret from RevenueCat pasted into Metriku
B) App does NOT use RevenueCat:
  - trackPaywallView + trackTrialStarted + trackTrialConverted (or trackPurchaseCompleted)
    + trackRenewed + trackCanceled + trackBillingGraceFailed at real moments

## Remote config & A/B
  Metriku.Config.whenReady { … }
  Metriku.Config.getBool / getInt / getJSON / getObjectArray / getObjectArray(fromJSON:field:)
  Multi-arm experiments (2–4 values of one key, e.g. free_quota_to_download=1/2/3) are
  assigned server-side — read the config key as usual; no special SDK multi-arm API.
  Metriku.Experiments.variant(experimentId)

## In-app messages
  Metriku.InAppMessages.fetchAndMaybePresent()

## Done checklist (in the app / Cursor)
1. Bundle ID is YOUR.BUNDLE.ID
2. App Key YOUR_APP_KEY in initialize
3. All screens/buttons/events instrumented; app_version + ios_version attributes set
4. If push: Notification Service Extension wired to MetrikuNotificationService.didReceive
5. If RevenueCat: iOS only login + trackPaywallView (webhook auth is configured in Metriku console next)
6. Run on a physical device → confirm Metriku Users / Analytics update

Do NOT invent API hosts, do NOT use GoogleService-Info.plist for Metriku server push,
do NOT add Metriku location/geofencing, and do NOT skip the Bundle ID match.

AFTER this prompt: return to Metriku → Project setup for optional Firebase (APNs .p8 + service account JSON)
and RevenueCat webhook (Bearer + HMAC) if you need push, in-app, or subscription data.

B · Push only

Wire Metriku push on this iOS target.
SPM: https://github.com/haxhiuurim/Metriku.git from 1.7.1 — import MetrikuSDK
Enable Push capability. After Metriku.initialize(APP_KEY, launchOptions:):
  Metriku.Notifications.requestPermission { _ in }
  // didRegisterForRemoteNotificationsWithDeviceToken:
  Metriku.Notifications.setPushToken(deviceToken)
  Metriku.Notifications.handleNotificationResponse(response) on taps
REQUIRED — Notification Service Extension:
  Add NSE target; SPM product MetrikuNotificationService on the extension;
  call MetrikuNotificationService.didReceive(request, contentHandler:) in didReceive
  so received notifications display with title/body/media (mutable-content).
print("Metriku deviceId", Metriku.User.deviceId())
Docs: https://metriku.dev/docs/ios#push
Upload APNs .p8 to Firebase Cloud Messaging, then Firebase service-account JSON to Metriku Settings.
Test from Metriku → Messages using the printed deviceId.

C · Funnel + RevenueCat (recommended)

Instrument Metriku WITH RevenueCat (UIKit or SwiftUI — match the project).
SDK: https://github.com/haxhiuurim/Metriku.git (1.7.1+) import MetrikuSDK
Initialize with App Key only (host https://metriku.dev).

DEFAULT ATTRIBUTES (always):
  app_version = CFBundleShortVersionString
  ios_version = UIDevice.current.systemVersion
  device_model = UIDevice.current.model
  platform = ios
  Metriku.User.setAttributes(["app_version": …, "ios_version": …, "device_model": …, "platform": "ios"])

FULL PRODUCT ANALYTICS (required — not just paywall):
  - Metriku.Analytics.screen on every screen (viewDidAppear / .onAppear)
  - Metriku.Analytics.trackButton on meaningful taps
  - Metriku.Analytics.track for feature/product events across the app

SUBSCRIPTIONS — ONLY THESE TWO APP CALLS when RC webhook is configured:
1) Metriku.login(sameUserIdAsRevenueCat.appUserID) after auth / Purchases.logIn
2) Metriku.Analytics.trackPaywallView() when the paywall is shown
DO NOT call trackTrial* / trackPurchase* / trackRenewed / trackCanceled / billing grace helpers.

WEBHOOK: Metriku Settings → copy URL → RC; configure BOTH:
  1) Bearer Authorization = Generate&save in Metriku → paste into RC Authorization field
  2) HMAC secret = enable in RC → paste into Metriku HMAC field
Verify Webhook log + Conversation funnel.

Docs: https://metriku.dev/docs/ios#funnel https://metriku.dev/docs/ios#revenuecat

D · Funnel without RevenueCat

This app does NOT use RevenueCat. Fill the Metriku Conversation funnel from the iOS SDK.
SDK: https://github.com/haxhiuurim/Metriku.git (1.7.1+) import MetrikuSDK
Initialize with App Key only (host https://metriku.dev).

Call at the matching product moments:
  Metriku.Analytics.trackPaywallView()
  Metriku.Analytics.trackTrialStarted()
  Metriku.Analytics.trackTrialConverted()        // after trial → paid
  // OR Metriku.Analytics.trackPurchaseCompleted() // paid with no trial
  Metriku.Analytics.trackRenewed()
  Metriku.Analytics.trackCanceled()
  Metriku.Analytics.trackBillingGraceFailed()    // if you have a grace UX

Do NOT connect a RevenueCat webhook for the same events (or you will double-count).
Custom events: Metriku.Analytics.track("feature_x_used", …)
Docs: https://metriku.dev/docs/ios#funnel