Skip to content

Latest commit

 

History

History
328 lines (239 loc) · 13.8 KB

File metadata and controls

328 lines (239 loc) · 13.8 KB

NetworkSpectator: Monitor and Inspect HTTP Traffic on iOS and macOS Apps

Swift 6.0+ Platforms SPM Compatible License: MIT Build

NetworkSpectator is a Swift network debugging library that intercepts, inspects, and logs HTTP/HTTPS requests and responses in your iOS or macOS app in real time. Browse captured API traffic in a native SwiftUI interface, view network request metrics, export logs, and create mock API responses programmatically or through the built-in UI. It is designed for developers debugging network calls during development and QA teams validating app behavior without backend dependencies.

Why NetworkSpectator

NetworkSpectator is for teams that need network debugging to go beyond a basic request list. It brings traffic capture, detailed inspection, mock responses, saved sessions, exports, and a native SwiftUI interface into one Swift Package, while still supporting lightweight mock-only integration when the full UI is not needed.

  • Useful across development and QA workflows

    • Developers can keep building against predictable responses when backend work is incomplete, unstable, or hard to reproduce
    • QA teams can create, reuse, and persist mock scenarios from the UI without asking for app code changes
  • Turns observed traffic into reusable mocks

    • Create mock responses directly from captured requests instead of recreating URLs, headers, and payloads manually
    • Register mocks programmatically when a scenario should be part of a repeatable development or test setup
  • Designed for deeper inspection

    • View headers, request payload, response, timeline metrics, transfer sizes, connection details, TLS information, and history
    • Export captured traffic as CSV, plain text, or Postman collections
    • Use on-demand monitoring when traffic capture should be enabled from the UI

Features

  • Real-time network monitoring

    • Capture URL, method, status code, response time, headers, request body, and response body
    • Network metrics including redirects, transaction timing, transfer sizes, connection details, and TLS information
    • Live updates with in-progress indicators for pending requests
    • Start immediately or use on-demand mode to enable monitoring from the UI when needed
    • Color-coded list view with method badges, status indicators, and response metrics
  • Filtering and search

    • Filter by status code ranges and HTTP methods
    • Combine multiple filters with visual filter chips
    • Full-text URL search across all captured requests
  • Detailed request inspection

    • Tabbed detail view: Overview, Request, Headers, Response and Metrics
    • Metrics view with summary, redirects, transactions and data transfers
    • Timeline phases for DNS, TCP, TLS, request, waiting and download timing
    • Connection details including protocol, TLS version, and cipher suite
    • Smart response rendering — pretty-printed JSON, inline image previews, and plain text
    • Copy any request or response data to clipboard
    • Create a mock response or logging exclusion directly from a captured request
  • Export in multiple formats

    • CSV — bulk or single request export for spreadsheets and analysis
    • Plain text — human-readable format for quick sharing
    • Postman Collection — import directly into Postman for API testing
  • Mock responses

    • Intercept requests and return custom responses without a backend
    • Flexible matching: hostname, URL, path, endPath, subPath
    • Configure status codes, headers, JSON/raw body, and response delay
    • Programmatic mocking — register mocks via code for unit tests and development
    • UI-based mocking — let QA testers create and manage mocks on the fly without Xcode
    • Persist mocks across app sessions with local storage
  • Logging exclusions

    • Exclude noisy or sensitive requests using the same flexible matching rules
    • Configure logging exclusions programmatically or from the UI
    • Persist exclusion rules across app launches
  • Insights dashboard

    • Summary cards: total requests, success rate, and unique hosts
    • Interactive charts for status code distribution, HTTP methods, host traffic, and request timeline
  • Log history

    • Automatically save session logs to disk for later review
    • Browse past sessions from Tools
    • Enable or disable history persistence from settings
  • Lightweight and easy to integrate

    • One-line setup to start monitoring
    • No XIB/Storyboards, no external dependencies
    • Works with SwiftUI, UIKit, and AppKit
    • Toggle debug console logging on or off
    • Supports both light and dark mode
  • Cross-platform

    • iOS 16.0+ / macOS 13.0+

Installation

Swift Package Manager

Add NetworkSpectator to your project using Swift Package Manager:

  1. In Xcode, select File > Add Package Dependencies...
  2. Enter the package repository URL - https://github.com/Pankajbawane/NetworkSpectator.git

Or add it to your Package.swift:

dependencies: [
    .package(url: "https://github.com/pankajbawane/NetworkSpectator.git", .upToNextMajor(from: "0.2.0"))
]

Architecture

NetworkSpectator is split into SwiftPM products so apps can depend on only the capabilities they need:

NetworkSpectatorCore <- NetworkSpectatorMocking <- NetworkSpectatorLogging <- NetworkSpectatorUI <- NetworkSpectator

The full NetworkSpectator product is the easiest integration path.

Products

Product Import Purpose
NetworkSpectator import NetworkSpectator You want the full capabilities: logging, mocking, persistence, exports through the UI, and the inspection interface.
NetworkSpectatorMocking import NetworkSpectatorMocking You only need in-memory mock responses without logging, persistence, exports, or UI.

Usage

Example App

The NetworkSpectatorExample app demonstrates basic usage of the library: https://github.com/Pankajbawane/NetworkSpectatorExample

Basic Setup

  1. Enable NetworkSpectator in your app's entry point (AppDelegate or App struct):

Call NetworkSpectator.start() to begin listening to HTTP requests. This will automatically log all HTTP traffic.

import NetworkSpectator
import SwiftUI

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .task {
                    #if DEBUG
                    NetworkSpectator.start()
                    #endif
                }
        }
    }
}
  1. Present the NetworkSpectator UI:

SwiftUI

import NetworkSpectator
import SwiftUI

struct ContentView: View {
    @State private var showLogs = false

    var body: some View {
        Button("Show Network Logs") {
            showLogs = true
        }
        .sheet(isPresented: $showLogs) {
            NetworkSpectator.rootView
        }
    }
}

UIKit (iOS)

import NetworkSpectator

let networkVC = NetworkSpectator.rootViewController
present(networkVC, animated: true)

AppKit (macOS)

import NetworkSpectator

let networkVC = NetworkSpectator.rootViewController
presentAsSheet(networkVC)

Configuration

Customize NetworkSpectator behavior with the configuration methods:

// Enable or disable diagnostic output in the Xcode console
NetworkSpectator.setDebugConsoleLogging(true)

// Register a mock response
NetworkSpectator.registerMock(for: mock)

// Remove all registered mocks
NetworkSpectator.clearMocks()

// Exclude matching requests from the captured request log
let exclusion = LoggingExclusionRule(method: .GET, rule: .hostName("analytics.example.com"))
NetworkSpectator.excludeFromLogging(for: exclusion)

// Remove all logging exclusions
NetworkSpectator.clearLoggingExclusions()

// Remove all registered mocks and logging exclusions
NetworkSpectator.reset()

On-Demand Monitoring

Start NetworkSpectator in on-demand mode to let users enable monitoring from the UI:

NetworkSpectator.start(onDemand: true)

Mock-Only Usage

Use NetworkSpectatorMocking when you only need in-memory mock responses and do not want logging, history persistence, exports, or UI:

import NetworkSpectatorMocking

let mock = Mock(
    method: .GET,
    rule: .url("https://api.example.com/users"),
    response: Data(#"{"users":[]}"#.utf8),
    headers: ["Content-Type": "application/json"],
    statusCode: 200,
    error: nil,
    saveLocally: false
)

NetworkSpectatorMocking.register(mock)
NetworkSpectatorMocking.start()

Stop mock-only interception when the mock session is no longer needed:

NetworkSpectatorMocking.stop()
NetworkSpectatorMocking.clearMocks()

The full facade exposes the same lifecycle for clients that already import NetworkSpectator:

NetworkSpectator.registerMock(for: mock)
NetworkSpectator.startMocking()
NetworkSpectator.stopMocking()

NetworkSpectatorMocking is memory-only. The Mock.saveLocally flag is kept on Mock for compatibility, but mock-only usage ignores it. Persisted mocks are handled by the logging/UI/full-facade flow through local storage.

Disabling NetworkSpectator

Call NetworkSpectator.stop() when network monitoring is no longer needed:

NetworkSpectator.stop()

NetworkSpectator on iOS

The following screenshots demonstrate NetworkSpectator running on iOS.

List of Requests Filters URL Search Details
landing filters_ios url_search_ios basic_ios
Headers Response Tools History
headers_ios response_response settings_ios share_ios
Insights Insights - Timeline Insights - Status code Insights - Performance
insights_ios timeline_ios status_code_ios perf_ios

NetworkSpectator on macOS

The following screenshots demonstrate NetworkSpectator running on macOS.

List of Requests Filters Details
landing_mac filters_mac basic_details_mac
Headers Response Tools
headers_mac response_mac analytics_mac
Insights Timeline Performance
settings_mac add_mock_mac skip_logging_mac

Safety and Release Builds

Because NetworkSpectator captures and displays network information, you should limit it to debug/test builds only. Wrap your integration points with #if DEBUG to ensure nothing leaks into release builds.

Recommendations

  • Always guard with #if DEBUG and/or internal feature flags
  • Ensure NetworkSpectator is not initialized in release configurations

Example

// Monitoring will start only for a debug build.
#if DEBUG
NetworkSpectator.start()
#endif

Requirements

  • Swift 6+
  • iOS 16.0+ / macOS 13.0+
  • Xcode 16.0+

LICENSE

MIT license. View LICENSE for more details.