# iOS quickstart

> Count events from an iPhone app through your own server and the server API, with a consent question, as Insights Orbit has no iOS SDK yet.

Source: https://docs.bifrostorbit.com/insights/developers/quickstart-ios/

Insights Orbit has no SDK for iOS yet. You can still count what people do in your app: the app tells your own server, and your server sends the event to the [server API](https://docs.bifrostorbit.com/insights/developers/server-api/) with an API key. In about 20 minutes you build a SwiftUI app for Northwilds that asks before counting, then sends **App opened** and **Brochure requested**.

The API key never goes into the app. Anyone can unpack an app and read what is inside it, and a key that sends events would let them send anything.

**Tested with:** Xcode 27.0, Swift 6 language mode, the iOS 26.3 Simulator, and Node.js 24 for the server.

## Before you start

You need:

- **A site in Insights Orbit** for the app. Events from your server carry no page address, so the site's addresses don't matter here. See [Add your first site](https://docs.bifrostorbit.com/insights/everyone/add-a-site/).
- **The site key**, from the site's **Install** screen.
- **An API key that sends events.** An Admin makes it under **API keys** with **Send events** ticked. It starts with `ins_live_` and is a secret. See [API keys](https://docs.bifrostorbit.com/insights/developers/api-keys/).
- **A server you control**, with Node.js 20 or later for this guide's example. Any language works: it is one `POST` request.
- **Xcode.**

## What you get, and what you don't

Server events count in **Events**, goals, revenue and the monthly events, like events from a website. They have no visitor and no visit, so the app doesn't change the numbers of visitors, visits or bounce rate, and there are no countries or devices: their device is `server`. Each event counts as a goal completion of its own.

## 1. Add an endpoint to your server

The app sends `{ id, name, properties }` to your server. The server checks the name against a list, adds the site key and passes it on with the API key:

```js
// analytics-relay.mjs
import { createServer } from 'node:http'

const INSIGHTS = process.env.INSIGHTS_URL ?? 'https://api.bifrostorbit.com/insights/v1'
const ALLOWED = new Set(['App opened', 'Brochure requested', 'Trip booked'])

createServer(async (request, response) => {
  if (request.method !== 'POST' || request.url !== '/analytics') return response.writeHead(404).end()
  let body = ''
  for await (const chunk of request) {
    body += chunk
    if (body.length > 10_000) return response.writeHead(413).end()
  }
  let event
  try {
    event = JSON.parse(body)
  } catch {
    return response.writeHead(400).end()
  }
  if (!ALLOWED.has(event?.name)) return response.writeHead(400).end()
  const answer = await fetch(`${INSIGHTS}/server/events`, {
    method: 'POST',
    headers: { authorization: `Bearer ${process.env.INSIGHTS_API_KEY}`, 'content-type': 'application/json' },
    body: JSON.stringify({ site: process.env.INSIGHTS_SITE, events: [{ id: event.id, name: event.name, properties: event.properties }] }),
  }).catch(() => null)
  if (!answer?.ok) console.warn('Insights Orbit did not take the event', answer?.status, await answer?.text())
  response.writeHead(answer?.ok ? 202 : 502).end()
}).listen(process.env.PORT ?? 3000)
```

Start it with the site key and the API key:

```bash
INSIGHTS_SITE=SITE_KEY INSIGHTS_API_KEY=ins_live_… node analytics-relay.mjs
```

- **The list of names** stops anyone who finds the endpoint from filling your reports with made-up events. Add each event the app sends.
- **`id`** comes from the app. The server API counts an id it has already seen in the last eight days once, so the app or your server can safely send again.
- **If your server already has an API**, add the same route there instead, as the [Laravel quickstart](https://docs.bifrostorbit.com/insights/developers/quickstart-laravel/) does in PHP.

**Check it:** `curl -X POST localhost:3000/analytics -d '{"id":"check-1","name":"App opened"}'` answers `202`, and a name that isn't on the list answers `400`.

## 2. Create the project

In Xcode, select **File › New › Project › App** and use:

- **Product Name:** `Northwilds`
- **Interface:** SwiftUI
- **Language:** Swift

## 3. Add the analytics client

```swift
// Analytics.swift
import Foundation

enum Analytics {
    static let endpoint = URL(string: "http://localhost:3000/analytics")!

    private struct Event: Encodable {
        let id: String
        let name: String
        let properties: [String: String]
    }

    static func track(_ name: String, _ properties: [String: String] = [:]) {
        guard UserDefaults.standard.bool(forKey: "analyticsAllowed") else { return }
        let event = Event(id: UUID().uuidString, name: name, properties: properties)
        Task.detached(priority: .utility) {
            var request = URLRequest(url: endpoint)
            request.httpMethod = "POST"
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.httpBody = try? JSONEncoder().encode(event)
            _ = try? await URLSession.shared.data(for: request)
        }
    }
}
```

- **`endpoint`** is your server. The Simulator reaches `http://localhost` on your Mac as it is. Before you ship, change it to your server's `https` address.
- **Nothing is sent until the person agrees** (step 4): `track` checks `analyticsAllowed` first.
- **The request runs in the background** and errors are ignored, so analytics never slows the app down or stops it.
- **Properties** are text here. Never send names, email addresses or other personal data. [Send your own events](https://docs.bifrostorbit.com/insights/developers/send-events/) has the limits.

## 4. Ask before counting

Insights Orbit reads nothing from the phone: the only data is what your app sends. Whether you ask first is your decision with your adviser; this app asks once and remembers the answer. Replace `ContentView.swift` with `TripView.swift`:

```swift
// TripView.swift
import SwiftUI

struct TripView: View {
    @AppStorage("analyticsAllowed") private var analyticsAllowed = false
    @AppStorage("analyticsAsked") private var analyticsAsked = false
    @State private var asking = false
    @State private var sent = false

    var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("Lofoten ski touring week").font(.title)
            Text("Seven days of ski touring above the fjords, from €2,450.")
            Button(sent ? "On its way" : "Send me the brochure") {
                Analytics.track("Brochure requested", ["trip": "lofoten-ski-touring"])
                sent = true
            }
            .disabled(sent)
        }
        .padding()
        .onAppear {
            if analyticsAsked { Analytics.track("App opened") } else { asking = true }
        }
        .alert("May we count how you use the app?", isPresented: $asking) {
            Button("Yes") {
                analyticsAllowed = true
                analyticsAsked = true
                Analytics.track("App opened")
            }
            Button("No thanks", role: .cancel) { analyticsAsked = true }
        } message: {
            Text("We keep no personal data.")
        }
    }
}
```

Show it from the app:

```swift
// NorthwildsApp.swift
import SwiftUI

@main
struct NorthwildsApp: App {
    var body: some Scene {
        WindowGroup {
            TripView()
        }
    }
}
```

- **Yes** stores the answer and sends **App opened** at once. Every later launch sends it too.
- **No thanks** stores the answer, and `track` sends nothing from then on. Give people a switch in your settings screen that changes `analyticsAllowed`, so they can change their mind.

## 5. Check that events arrive

Run the app in the Simulator, select **Yes**, then **Send me the brochure**.

- **In Insights Orbit:** **Events** lists **App opened** and **Brochure requested** within a few seconds. Open one to see its details, such as `trip`.
- **On your server:** a refused event prints `Insights Orbit did not take the event` with the status, such as `401` for a wrong key.
- **From the API**, on the Growth plan, with a key that reads events:

```bash
curl "https://api.bifrostorbit.com/insights/v1/events?site=SITE_KEY&name=Brochure%20requested" \
  -H "Authorization: Bearer ins_live_…"
```

The event comes back with `"device": "server"` and its `properties`.

To try **No thanks**, delete the app from the Simulator and run it again: the question comes back, and after **No thanks** nothing reaches your server.

## Next steps

- [Send events from a server](https://docs.bifrostorbit.com/insights/developers/server-api/): every field, including `revenue`, `timestamp` and `userId`.
- [Set up goals](https://docs.bifrostorbit.com/insights/everyone/goals/): count **Brochure requested** as success.
- [Android quickstart](https://docs.bifrostorbit.com/insights/developers/quickstart-android/): the same for Android.
- [Read raw events](https://docs.bifrostorbit.com/insights/developers/raw-event-api/): every event for your own data tools.
