Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
70 lines (57 sloc) 1.9 KB
title menu category order permalink
Track events in iOS via Swift or Objective-C
Track events in iOS

This is a draft of how to track events with iOS. If you know how to improve it, please let us know.

import Foundation

class Analytics: NSObject {

    private struct EventData: Encodable {
        let v: Int = 1
        let ua: String = "ios"
        let platform: String = "ios"
        let hostname: String = ""
        let date: Date = Date()
        let events: [String]

    private static let encoder: JSONEncoder = {
        let encoder = JSONEncoder()
        encoder.keyEncodingStrategy = .convertToSnakeCase
        encoder.dateEncodingStrategy = .formatted(dateFormatter)
        return encoder

    private static let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter

    static func log(eventName: String) {
        Analytics.log(eventNames: [eventName])

    static func log(eventNames: [String]) {
        let eventData = EventData(events: eventNames)

        guard let jsonData = try? encoder.encode(eventData) else {
            print("Error while logging event: unable to convert event to JSON")

        let url = URL(string: "")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if let error = error {
                print("Error while logging event: \(error)")

You can’t perform that action at this time.