Skip to content

Repository files navigation

PhantomSwift Logo

PHANTOM SWIFT

The Elite, Zero-Dependency iOS Debugging & Diagnostic Toolkit

Version 1.2.0MIT LicenseZero Dependencies25 ModulesDEBUG onlySwift VersionsSupported Platforms

PhantomSwift is an open-source iOS debugging library for Swift developers. It provides network inspection, memory leak detection, UI hierarchy exploration, and 25+ diagnostic tools — all in a single zero-dependency package. Compatible with UIKit and SwiftUI, installable via SPM or CocoaPods, with a minimum runtime target of iOS 13 and a validated Swift 5.9+ toolchain.


Overview

PhantomSwift is a professional-grade, modular debugging ecosystem for iOS apps. It ships 25 rich modules — from network inspection and performance profiling to remote WebSocket debugging and macro recording — all wrapped in a premium glassmorphic UI. Every line of code is compiled only in DEBUG builds, so it adds zero overhead to your production binary.

Why PhantomSwift?

PhantomSwiftFLEXPulseNetfox
Zero dependencies
#if DEBUG safe
Network inspection
3D view hierarchy
Performance monitoring
Request interception
Bad network simulation
Feature flags
Remote WebSocket server
Memory leak tracker
Macro recorder
Security audit
Bug reporter
Glassmorphic UI
Module count25~8~51

Looking for an Alternative?

  • FLEX alternative — PhantomSwift covers everything FLEX does, plus network mocking, bad network simulation, feature flags, and a glassmorphic UI.
  • Netfox replacement — PhantomSwift includes all Netfox's network inspection with 25 additional modules, and is also #if DEBUG safe.
  • Pulse iOS alternative — PhantomSwift adds zero-dependency constraint with full UIKit + SwiftUI support and no external packages required.

Key Principles

  • Zero external dependencies — built entirely with Apple frameworks
  • #if DEBUG safe — every file is wrapped; nothing ships to the App Store
  • iOS 13+ runtime support — with #available guards for newer APIs
  • Swift 5.x aligned — validated with Swift 5.9+ toolchains
  • Glassmorphic UI — premium dark theme with blur, shadows, and micro-animations
  • Modular architecture — enable or disable any module independently

Table of Contents


Screenshots

DashboardNetwork TracePerformance

3D View HierarchyStorage InspectorConsole Logger

InterceptorsSecurity AuditMemory Graph


Features

Connectivity & API

ModuleDescription
Network TraceReal-time HTTP/HTTPS traffic monitoring with full request/response inspection, HAR export, and search/filter
InterceptorMock, block, delay, or redirect any request. Mockoon redirect support. Hit counters and exclude patterns
Bad NetworkSimulate poor connectivity (3G, Edge, packet loss, latency) with one tap
Network WaterfallChrome DevTools-style waterfall timeline showing request durations and concurrency
Request ReplayEdit and replay any captured request. Save responses as mock rules
HAR ExportExport network traces as HAR 1.2 JSON files for sharing with backend teams

Performance & Diagnostics

ModuleDescription
Performance MonitorReal-time CPU, FPS, and RAM tracking with interactive timeline graphs
Hang DetectorMain-thread freeze detection (>400ms) with full call stack capture
Main Thread CheckerDetects UIKit calls from background threads via method swizzling
Memory Leak TrackerAutomatic retain cycle detection with object lifecycle tracking
Memory Graph & DiffVisual object relationship explorer and heap snapshot comparator

UI & Design Systems

ModuleDescription
UI InspectorLive property inspection with constraint details, measurement tool
3D View HierarchyXcode-style exploded 3D view with tap-to-select, depth slider, wireframe toggle, and pinch-to-zoom
SwiftUI Render TrackerTrack re-render frequency per SwiftUI component
Asset InspectorAudit image/video assets for memory optimization and sizing
Accessibility AuditScan for missing labels, small touch targets, and A11y violations
Layout ConflictDetect and display Auto Layout constraint conflicts in real-time

Storage & State

ModuleDescription
Storage InspectorBrowse and edit UserDefaults, Keychain, sandbox files, and SQLite databases
State SnapshotSave entire app state (defaults, files) and restore it instantly

Developer Toolkit

ModuleDescription
Console LoggerPriority-level logging with tags, metadata, and full-text search
Analytics InterceptorIntercept and inspect analytics events (Firebase, Amplitude, custom)
Feature FlagsRegister, toggle, and persist feature flags with grouped UI
Bug ReporterAnnotate screenshots with freehand drawing, export diagnostic bundles
Macro RecorderRecord touch sequences and replay them for QA regression testing
Remote ServerWebSocket debug server for real-time remote inspection
Security AuditJailbreak detection, SSL pinning check, and binary integrity verification
Environment SwapperSpoof GPS, change locale, monitor battery/thermal state
Runtime BrowserBrowse Objective-C classes, methods, and properties at runtime
Push Notification TesterSimulate and test push notifications locally
Deeplink TesterTest URL schemes and universal links without leaving the app

Installation

Swift Package Manager (Recommended)

Add PhantomSwift via Xcode:

  1. File → Add Package Dependencies...
  2. Enter the repository URL:
    https://github.com/synaptode/PhantomSwift.git
    
  3. Select version rule: Up to Next Major
  4. Add to your Debug target only

Or add it to your Package.swift:

dependencies:[.package(url:"https://github.com/synaptode/PhantomSwift.git", from:"1.2.0")]

CocoaPods

pod'PhantomSwift',:configurations=>['Debug']

Important: Always add PhantomSwift to your Debug configuration only. All code is wrapped in #if DEBUG, but restricting the dependency ensures zero bytes in release builds.

Compatibility: PhantomSwift supports iOS 13.0+ at runtime. The current package manifest and CocoaPods spec are validated with Swift 5.9+ toolchains, which keeps the library within the Swift 5 generation while matching the repo's actual build settings.


Quick Start

SwiftUI

import SwiftUI
#if DEBUGimport PhantomSwift
#endif@mainstructMyApp:App{init(){#if DEBUGPhantomSwift.configure{ config in
config.environment =.dev
config.triggers =[.shake,.dynamicIsland]
config.theme =.dark
}PhantomSwift.launch()#endif}varbody:someScene{WindowGroup{ContentView()}}}

UIKit

import UIKit
#if DEBUGimport PhantomSwift
#endif@mainclassAppDelegate:UIResponder,UIApplicationDelegate{func application(_ application:UIApplication,
didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey:Any]?)->Bool{#if DEBUGPhantomSwift.configure{ config in
config.environment =.dev
config.triggers =[.shake]
config.theme =.dark
config.shortcuts =[AppShortcut(title:"Clear Cache"){URLCache.shared.removeAllCachedResponses()}]}PhantomSwift.launch()#endifreturntrue}}

Accessing the Dashboard

TriggerHow
ShakeShake your device (default trigger)
Dynamic IslandTap the floating pill overlay

Both triggers can be configured via config.triggers.


Modules in Detail

📋 Dashboard

The central hub for all PhantomSwift modules. A Niagara-style A→Z scrollable grid displays every available module with a glassmorphic card UI.

PhantomSwift Dashboard

The dashboard provides quick access to all 25 modules. Each card shows the module icon, name, and a brief description. Enabled modules are highlighted with a colored accent glow.


🌐 Network Trace

Automatically captures all HTTP/HTTPS traffic via URLProtocol swizzling. Provides a detailed view of every request and response flowing through your app.

Network ListNetwork OverviewNetwork HeadersNetwork Body

Capabilities:

  • Full request/response body inspection with JSON pretty-printing
  • Status code color-coding (2xx green, 4xx orange, 5xx red)
  • Header inspection with copy-to-clipboard
  • Text search and status code filtering
  • HAR 1.2 export for sharing with backend teams
  • Request edit & replay
  • Automatic content-type detection (JSON, XML, HTML, image)

🚧 Interceptor

Create rules to intercept matching network requests. Supports multiple interception strategies to simulate various backend scenarios without modifying server code.

Interceptor Rules

Rule Types:

TypeDescription
MockReturn a custom JSON/text response body
BlockPrevent the request from executing entirely
RedirectForward to a different URL (e.g., Mockoon server)
DelayAdd artificial latency (100ms – 30s)

Features:

  • URL pattern matching with wildcards
  • Hit counter per rule
  • Exclude patterns to bypass specific endpoints
  • Per-rule enable/disable toggle
  • Import/export rule sets

📡 Bad Network Simulator

Simulate poor network conditions to test your app’s resilience — no proxy tools or extra setup required.

Bad Network Simulation

Presets:

ProfileLatencyThroughputPacket Loss
WiFi2msUnlimited0%
4G/LTE50ms12 Mbps1%
3G200ms1.6 Mbps2%
Edge400ms240 Kbps5%
GPRS500ms50 Kbps10%
Offline0100%

All parameters (latency, throughput, packet loss) are individually adjustable with sliders for custom profiles.


📊 Network Waterfall

Chrome DevTools-style waterfall timeline showing request durations and concurrency — a visual overview of how your network requests overlap in time.

Network Waterfall

What it shows:

  • DNS lookup, connection, SSL, TTFB, and content download phases
  • Concurrent request overlap visualization
  • Color-coded bars by content type (API, image, script)
  • Total page load time calculation
  • Tap any bar to jump to the full request detail

⚡ Performance Monitor

Real-time CPU, FPS, and RAM tracking with interactive timeline graphs. Spot performance bottlenecks as they happen.

Performance Monitor

Metrics tracked:

  • CPU Usage — per-process CPU utilization percentage
  • FPS — frames per second from CADisplayLink (drops highlighted in red)
  • Memory — resident set size (RSS) in MB with peak tracking
  • Thermal State — device thermal state monitoring (nominal → critical)

Interactive timeline lets you scrub through the last 60 seconds of data. Anomalies (FPS drops, CPU spikes, memory warnings) are highlighted with markers.


📝 Console Logger

A priority-level logging system with tags, metadata, and full-text search. Replaces print() with structured, filterable output.

Console Logger

Usage:

#if DEBUGPhantomLog.debug("View loaded", tag:"UI")PhantomLog.info("User signed in", tag:"Auth")PhantomLog.warning("Cache miss for key: \(key)", tag:"Cache")PhantomLog.error("Failed to decode response", tag:"Network")#endif

Features:

  • Five priority levels: verbose, debug, info, warning, error
  • Tag-based filtering (e.g., show only "Network" logs)
  • Full-text search across all log entries
  • Timestamp with millisecond precision
  • Export logs as text file
  • OSLog bridge for unified logging (iOS 14+)
  • Plug-and-play WKWebView console capture for console.log, console.warn, console.error, and JS bridge payloads

Plug-and-play for hybrid HTML/native apps:

After PhantomSwift.launch(), new WKWebView instances are instrumented automatically when the Logger module is enabled. That means browser-side logs like console.log("bridge ready") and console.error("checkout failed", payload) will appear in PhantomSwift's Console Logger without you wiring each web view manually.

If you want explicit control over handler naming or tagging, you can still install the bridge yourself:

import WebKit
#if DEBUGimport PhantomSwift
#endiffinalclassCheckoutWebVC:UIViewController{#if DEBUGprivateletphantomConsoleBridge=PhantomWebViewConsoleBridge(
configuration:.init(handlerName:"phantomConsole", tag:"CheckoutJS"))#endifprivate lazy varwebView:WKWebView={letconfiguration=WKWebViewConfiguration()#if DEBUG
phantomConsoleBridge.install(into: configuration)#endifreturnWKWebView(frame:.zero, configuration: configuration)}()}

If you already have your own JS bridge, you can also forward messages manually from native:

#if DEBUGPhantomWebViewConsoleBridge.capture(
level:.error,
message:"window.checkoutBridge rejected payload",
tag:"CheckoutJS",
sourceURL: webView.url?.absoluteString
)#endif

You can disable the automatic mode if your host app needs stricter ownership over WKWebView setup:

#if DEBUGPhantomSwift.configure{ config in
config.enableAutomaticWebViewConsoleBridge =false}#endif

🔍 UI Inspector & 3D Hierarchy

Inspect any view in your app hierarchy — tap to select, view properties, constraints, and spatial relationships. The 3D exploded view provides an Xcode-style visualization of the entire view tree.

View TreeSelected ViewView Detail

UI Inspector features:

  • Tap-to-select any view in the hierarchy
  • Property inspection: frame, bounds, alpha, backgroundColor, accessibilityLabel
  • Constraint list with priority, constant, multiplier
  • Live editing of properties (frame, alpha, backgroundColor)
  • Measurement tool — measure distance between any two views

3D HierarchyMeasurement ToolLive Edit

3D Hierarchy features:

  • Exploded 3D view with adjustable spacing
  • Depth filter slider to focus on specific layers
  • Rotate X/Y sliders for precise camera control
  • Wireframe mode to see layout structure
  • Class name labels overlay
  • Tap any layer to open the inspector sheet
  • Pinch to zoom, 1-finger pan, 2-finger orbit
  • Fit All & Reset camera controls
  • Mini-map overlay for orientation

🧠 Memory Leak Tracker & Graph

Automatic retain cycle detection with object lifecycle tracking. The memory graph visualizes object relationships to help identify where leaks occur.

Memory Leak TrackerMemory Graph

Leak Tracker:

  • Tracks UIViewController and UIView lifecycle via swizzling
  • Detects objects that are not deallocated after dismissal (potential leaks)
  • Shows class name, allocation time, and retain count
  • Configurable detection delay (default: 3s after dismissal)

Memory Graph:

  • Visual directed graph of object references
  • Interactive nodes — tap to inspect properties
  • Snapshot comparison (diff between two heap states)
  • Highlights potential retain cycles with red edges

💾 Storage Inspector

Browse and edit all local storage mechanisms from a single interface.

Storage Inspector

Supported storage types:

StorageCapabilities
UserDefaultsBrowse, edit, delete keys. Type-aware editing (String, Int, Bool, Date, Array, Dictionary)
KeychainRead and delete keychain items. Filtered by app’s access group
Sandbox FilesNavigate the app’s Documents, Library, and tmp directories. View file contents, sizes, dates
SQLiteBrowse tables, execute raw SQL queries, view schema

All edits are reflected immediately — no app restart needed.


📈 Analytics Interceptor

Intercept and inspect analytics events from any provider without modifying your analytics code.

Analytics FeedAnalytics by Provider

Supported providers:

  • Firebase Analytics
  • Amplitude
  • Mixpanel
  • Custom event buses

Features:

  • Real-time event feed with timestamp, name, and parameters
  • Group-by-provider view to see event distribution
  • Search and filter by event name or parameter value
  • Event validation — warns about missing required parameters

🚩 Feature Flags

Runtime feature flag management with a beautiful grouped UI. Toggle features on-the-fly without recompilation.

#if DEBUG
// Register flags at launch
PhantomFeatureFlags.shared.register(key:"new_onboarding", title:"New Onboarding Flow",
defaultValue:false, group:"UX")PhantomFeatureFlags.shared.register(key:"dark_mode_v2", title:"Dark Mode V2",
defaultValue:true, group:"Theme")
// Check flags anywhere
ifPhantomFeatureFlags.shared.isEnabled("new_onboarding"){showNewOnboarding()}#endif

Features:

  • Register flags with key, title, description, default value, and group
  • Toggle overrides from the dashboard with immediate effect
  • Overrides persist across app launches via UserDefaults
  • Reset individual flags or all at once
  • Override badge count shown on the dashboard card

🔒 Security Audit

Comprehensive security analysis of your app’s runtime environment.

Security Audit OverviewSecurity Audit Details

Checks performed:

CheckDescription
Jailbreak DetectionChecks for Cydia, unusual paths, writable system dirs
SSL PinningValidates certificate pinning implementation
Debugger DetectionDetects if a debugger is attached
Binary IntegrityChecks code signature and encryption status
Keychain SecurityValidates keychain access control settings
App Transport SecurityChecks ATS exceptions in Info.plist

Results are color-coded: 🟢 Pass, 🟡 Warning, 🔴 Fail — with remediation suggestions.


🖼 Asset Inspector

Audit image and video assets for memory optimization, sizing, and potential issues.

Asset Inspector

Analysis includes:

  • Image dimensions vs. display size (flags oversized images)
  • Memory footprint calculation per asset
  • Format identification (PNG, JPEG, HEIF, WebP, PDF)
  • Missing @2x/@3x variants detection
  • Total asset catalog size summary

🌍 Environment Swapper

Override device environment settings for testing — no need to physically move or change device settings.

Environment OverviewGPS SpoofingLocale Override

Capabilities:

  • GPS Spoofing — Set custom coordinates for location-dependent features
  • Locale Override — Change app locale without changing device settings
  • Battery Monitoring — Real-time battery level and charging state
  • Thermal State — Monitor device temperature state
  • Time Zone Override — Test time-sensitive features across zones

🔬 Runtime Browser

Browse Objective-C classes, methods, and properties at runtime — a powerful introspection tool for understanding third-party SDKs.

Runtime Browser

Features:

  • Browse all loaded Objective-C classes
  • Inspect instance methods, class methods, and properties
  • View method signatures and return types
  • Search by class name or method name
  • Filter by framework/module

⚠️ Layout Conflict Detector

Detects Auto Layout constraint conflicts in real-time and displays them in a clear, actionable format.

Layout Conflict

Features:

  • Captures UIViewAlertForUnsatisfiableConstraints breakpoint output
  • Parses conflicting constraint sets into readable format
  • Shows which views and constraints are involved
  • Suggests which constraint to remove or lower priority

🔔 Push Notification Tester

Simulate and test push notifications locally without a backend or APNs configuration.

Push Notification Tester

Features:

  • Create custom notification payloads (title, body, badge, sound)
  • Schedule local notifications with configurable delay
  • Test deep link routing from notification taps
  • Preview notification appearance before sending

🔗 Deeplink Tester

Test URL schemes and universal links without leaving the app.

Deeplink Tester

Features:

  • Input any URL scheme or universal link
  • Execute deep links within the app context
  • History of recently tested links
  • Quick-access bookmarks for frequently tested routes

🖥 Remote WebSocket Server

Start a WebSocket server on the device. Connect from any WebSocket client (browser, Postman, custom tool) and query your app’s state in real time.

#if DEBUGif #available(iOS 13.0,*){PhantomRemoteServer.shared.start(port:9876)}
// Connect from browser: ws://<device-ip>:9876
// Send JSON: {"command": "logs"} or {"command": "network-trace"}
#endif

Available Commands:

CommandDescription
app-infoApp bundle info, device model, iOS version
system-statusCPU, memory, disk usage
logsLast 50 log entries
network-traceLast 50 network requests
feature-flagsAll registered feature flags
toggle-flagToggle a feature flag (params: key)
performanceCurrent metrics + 30-sample history
clear-logsClear the log store
clear-networkClear captured network requests
helpList available commands

A built-in web echo page is included at Resources/web-echo/index.html for quick browser-based testing.


Architecture

Sources/PhantomSwift/
├── Core/ # Framework core
│ ├── PhantomSwift.swift # Main entry point & setup
│ ├── PhantomFeature.swift # Feature enum (25 cases)
│ ├── PhantomEventBus.swift # Thread-safe event system
│ ├── PhantomConfig.swift # Configuration struct
│ ├── PhantomEnvironment.swift # Environment enum
│ └── PhantomPlugin.swift # Plugin protocol
├── HUD/ # Dashboard & presentation
│ ├── PhantomDashboardVC.swift # Niagara-style A→Z dashboard
│ ├── PhantomTheme.swift # Glassmorphic design tokens
│ ├── PhantomHUDWindow.swift # Overlay window management
│ ├── PhantomGestureHandler.swift # Shake/Dynamic Island trigger
│ └── PhantomDynamicIsland.swift # Dynamic Island floating pill
├── Modules/ # Feature modules
│ ├── Network/ # Network trace, waterfall, HAR, replay
│ ├── Interceptor/ # Request mocking & redirection
│ ├── Logger/ # Console logger with levels & tags
│ ├── Performance/ # CPU/FPS/RAM monitor & timeline
│ ├── MemoryLeak/ # Leak tracker & object graph
│ ├── UIInspector/ # UI inspection & 3D hierarchy
│ ├── Storage/ # UserDefaults, Keychain, SQLite, Sandbox
│ ├── QA/ # Bug reporter, macro recorder, shortcuts
│ ├── Security/ # Security audit & checks
│ ├── Analytics/ # Analytics event interceptor
│ ├── SwiftUI/ # Render body tracker
│ ├── FeatureFlags/ # Feature flag management
│ ├── MainThreadChecker/ # Background thread violation detection
│ ├── RuntimeBrowser/ # ObjC runtime introspection
│ ├── Assets/ # Asset inspector & optimization
│ ├── Remote/ # WebSocket debug server
│ └── Core/ # Extension bus & shared module utils
└── Shared/ # Shared utilities
├── Components/ # Reusable UI (PhantomTableVC, badges, code view)
├── Extensions/ # UIColor+Phantom, UIFont+Phantom, etc.
└── Helpers/ # Swizzler, formatters, utilities

Design Patterns

PatternUsage
SingletonsModule managers (PhantomLog.shared, PhantomFeatureFlags.shared)
Event BusPhantomEventBus for decoupled module communication
Thread SafetyDispatchQueue(attributes: .concurrent) with .barrier writes
Base VCPhantomTableVC for consistent list UIs across modules
Theme SystemPhantomTheme for centralized styling — never hardcode colors
SwizzlerPhantomSwizzler for safe method swizzling

Configuration

PhantomSwift.configure{ config in
// Environment (default: .dev)
config.environment =.dev // .dev | .staging | .release
// Dashboard triggers
config.triggers =[.shake,.dynamicIsland]
// Theme
config.theme =.dark // .dark | .light | .auto
// Custom QA shortcuts
config.shortcuts =[AppShortcut(title:"Reset Onboarding"){UserDefaults.standard.removeObject(forKey:"hasSeenOnboarding")},AppShortcut(title:"Force Crash"){fatalError("Debug crash triggered")}]}

Configuration Options

OptionTypeDefaultDescription
environmentPhantomEnvironment.devCurrent build environment
triggers[PhantomTrigger][.shake]How to open the dashboard
themePhantomThemeMode.darkUI theme mode
shortcuts[AppShortcut][]Custom QA actions in dashboard

Requirements

RequirementMinimum
iOS13.0+
Swift5.9+
Xcode15.0+
DependenciesNone

iOS Compatibility Notes:

  • iOS 13+: Core functionality uses SF Symbols directly with no emoji fallbacks.
  • iOS 13+: Full SF Symbols, UINavigationBarAppearance, monospaced digit fonts.
  • iOS 13+: Remote WebSocket Server requires Network.framework (NWListener).
  • iOS 14+: OSLog bridge for unified logging.

Swift Compatibility Notes:

  • Swift 5.x: PhantomSwift is maintained in the Swift 5 family.
  • Swift 5.9+: Current package manifest, CocoaPods spec, CI verification, and documentation are validated against Swift 5.9+ toolchains.

Contributing

Contributions are welcome! Please follow these guidelines:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Commit with clear messages: git commit -m "Add: macro recorder export as JSON"
  4. Push to your fork: git push origin feature/my-feature
  5. Open a Pull Request

Code Standards

  • Wrap ALL code in #if DEBUG / #endif
  • Use PhantomTheme.shared for colors/fonts — never hardcode
  • Use [weak self] in closures that may outlive the caller
  • No force unwraps (!) — use guard/if let
  • Use PhantomSwizzler for method swizzling
  • Prefix public types with Phantom
  • Build UI programmatically — no storyboards or XIBs
  • Use NSLayoutConstraint.activate([...]) for Auto Layout
  • Wrap iOS 13+ APIs in if #available(iOS 13.0, *)

License

PhantomSwift is released under the MIT License. See LICENSE for details.


Built with precision for iOS engineers who demand the best debugging tools.

About

iOS debug toolkit: network inspector, memory leak tracker, UI hierarchy, 25 modules. Zero deps. SPM + CocoaPods. #if DEBUG safe.

Topics

Resources

Stars

6 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages