Collect events on iOS with Swift edit

Download PDF

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

This is deprecated and only left for historical purposes.

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)")


Make sure to include a user agent in the headers of the request. This is not included in the example above.

Thanks to Rutger Bresjer from Woost Technologies for providing above code example.