iOS SDK ⁠-⁠ Intercepting the network

ORTracker exports NetworkListener that accepts both, tasks and requests, here’s how you do it:

import ORTracker

func fetchPokemonData(for name: String) {
    let networkListener = NetworkListener()
    let url = URL(string: "https://pokeapi.co/api/v2/pokemon/ditto")!
    var request = URLRequest(url: url)
    request.httpMethod = "GET" // This is the default, so it's optional in this case.

    // Start the network listener with the request
    networkListener.start(request: request)

    // Create a data task
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            return
        }
        
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print("Error deserializing JSON: \(error)")
            }
        }
        
        networkListener.finish(response: response, data: data)
    }

    task.resume()

  }

Two keys are exported to automatically trim the request/response data: ignoredKeys for body and ignoredHeaders for headers. Both, request and response will be sanitized, but body will only be affected if its a valid JSON.

Simply assign a list of strings that you would like to sanitize:

let networkListener = NetworkListener()
networkListener.ignoredHeaders = ["mySecretToken"]
networkListener.ignoredKeys = ["password"]

It is also possible to change the response data before passing it to the listener:

// ... request

var sanitizedData
if let data = data {
  do {
    let json = try JSONSerialization.jsonObject(with: data, options: [])
    sanitizedData = customSanitizeFunction(data)
    print(json)
  } catch {
    print("Error deserializing JSON: \(error)")
  }
}

networkListener.finish(response: response, data: sanitizedData)