axiom-networking

0
0
Source

Use when implementing Network.framework connections, debugging connection failures, migrating from sockets/URLSession streams, or adopting structured concurrency networking patterns - prevents deprecated API usage, reachability anti-patterns, and thread-safety violations with iOS 12-26+ APIs

Install

mkdir -p .claude/skills/axiom-networking && curl -L -o skill.zip "https://mcp.directory/api/skills/download/7377" && unzip -o skill.zip -d .claude/skills/axiom-networking && rm skill.zip

Installs to .claude/skills/axiom-networking

About this skill

Network.framework Networking

When to Use This Skill

Use when:

  • Implementing UDP/TCP connections for gaming, streaming, or messaging apps
  • Migrating from BSD sockets, CFSocket, NSStream, or SCNetworkReachability
  • Debugging connection timeouts or TLS handshake failures
  • Supporting network transitions (WiFi ↔ cellular) gracefully
  • Adopting structured concurrency networking patterns (iOS 26+)
  • Implementing custom protocols over TLS/QUIC
  • Requesting code review of networking implementation before shipping

Related Skills

  • Use axiom-networking-diag for systematic troubleshooting of connection failures, timeouts, and performance issues
  • Use axiom-network-framework-ref for comprehensive API reference with all WWDC examples

Example Prompts

1. "How do I migrate from SCNetworkReachability? My app checks connectivity before connecting."

2. "My connection times out after 60 seconds. How do I debug this?"

3. "Should I use NWConnection or NetworkConnection? What's the difference?"


Red Flags — Anti-Patterns to Prevent

If you're doing ANY of these, STOP and use the patterns in this skill:

❌ CRITICAL — Never Do These

1. Using SCNetworkReachability to check connectivity before connecting

// ❌ WRONG — Race condition
if SCNetworkReachabilityGetFlags(reachability, &flags) {
    connection.start() // Network may change between check and start
}

Why this fails Network state changes between reachability check and connect(). You miss Network.framework's smart connection establishment (Happy Eyeballs, proxy handling, WiFi Assist). Apple deprecated this API in 2018.

2. Blocking socket operations on main thread

// ❌ WRONG — Guaranteed ANR (Application Not Responding)
let socket = socket(AF_INET, SOCK_STREAM, 0)
connect(socket, &addr, addrlen) // Blocks main thread

Why this fails Main thread hang → frozen UI → App Store rejection for responsiveness. Even "quick" connects take 200-500ms.

3. Manual DNS resolution with getaddrinfo

// ❌ WRONG — Misses Happy Eyeballs, proxies, VPN
var hints = addrinfo(...)
getaddrinfo("example.com", "443", &hints, &results)
// Now manually try each address...

Why this fails You reimplement 10+ years of Apple's connection logic poorly. Misses IPv4/IPv6 racing, proxy evaluation, VPN detection.

4. Hardcoded IP addresses instead of hostnames

// ❌ WRONG — Breaks proxy/VPN compatibility
let host = "192.168.1.1" // or any IP literal

Why this fails Proxy auto-configuration (PAC) needs hostname to evaluate rules. VPNs can't route properly. DNS-based load balancing broken.

5. Ignoring waiting state — not handling lack of connectivity

// ❌ WRONG — Poor UX
connection.stateUpdateHandler = { state in
    if case .ready = state {
        // Handle ready
    }
    // Missing: .waiting case
}

Why this fails User sees "Connection failed" in Airplane Mode instead of "Waiting for network." No automatic retry when WiFi returns.

6. Not using [weak self] in NWConnection completion handlers

// ❌ WRONG — Memory leak
connection.send(content: data, completion: .contentProcessed { error in
    self.handleSend(error) // Retain cycle: connection → handler → self → connection
})

Why this fails Connection retains completion handler, handler captures self strongly, self retains connection → memory leak.

7. Mixing async/await and completion handlers in NetworkConnection (iOS 26+)

// ❌ WRONG — Structured concurrency violation
Task {
    let connection = NetworkConnection(...)
    connection.send(data) // async/await
    connection.stateUpdateHandler = { ... } // completion handler — don't mix
}

Why this fails NetworkConnection designed for pure async/await. Mixing paradigms creates difficult error propagation and cancellation issues.

8. Not supporting network transitions

// ❌ WRONG — Connection fails on WiFi → cellular transition
// No viabilityUpdateHandler, no betterPathUpdateHandler
// User walks out of building → connection dies

Why this fails Modern apps must handle network changes gracefully. 40% of connection failures happen during network transitions.


Mandatory First Steps

ALWAYS complete these steps before writing any networking code:

// Step 1: Identify your use case
// Record: "UDP gaming" vs "TLS messaging" vs "Custom protocol over QUIC"
// Ask: What data am I sending? Real-time? Reliable delivery needed?

// Step 2: Check if URLSession is sufficient
// URLSession handles: HTTP, HTTPS, WebSocket, TCP/TLS streams (via StreamTask)
// Network.framework handles: UDP, custom protocols, low-level control, peer-to-peer

// If HTTP/HTTPS/WebSocket → STOP, use URLSession instead
// Example:
URLSession.shared.dataTask(with: url) { ... } // ✅ Correct for HTTP

// Step 3: Choose API version based on deployment target
if #available(iOS 26, *) {
    // Use NetworkConnection (structured concurrency, async/await)
    // TLV framing built-in, Coder protocol for Codable types
} else {
    // Use NWConnection (completion handlers)
    // Manual framing or custom framers
}

// Step 4: Verify you're NOT using deprecated APIs
// Search your codebase for these:
// - SCNetworkReachability → Use connection waiting state
// - CFSocket → Use NWConnection
// - NSStream, CFStream → Use NWConnection
// - NSNetService → Use NWBrowser or NetworkBrowser
// - getaddrinfo → Let Network.framework handle DNS

// To search:
// grep -rn "SCNetworkReachability\|CFSocket\|NSStream\|getaddrinfo" .

What this tells you

  • If HTTP/HTTPS: Use URLSession, not Network.framework
  • If iOS 26+ deployment: Use NetworkConnection with async/await
  • If iOS 12-25 support needed: Use NWConnection with completion handlers
  • If any deprecated API found: Must migrate before shipping (App Store review concern)

Decision Tree

Use this to select the correct pattern in 2 minutes:

Need networking?
├─ HTTP, HTTPS, or WebSocket?
│  └─ YES → Use URLSession (NOT Network.framework)
│     ✅ URLSession.shared.dataTask(with: url)
│     ✅ URLSession.webSocketTask(with: url)
│     ✅ URLSession.streamTask(withHostName:port:) for TCP/TLS
│
├─ iOS 26+ and can use structured concurrency?
│  └─ YES → NetworkConnection path (async/await)
│     ├─ TCP with TLS security?
│     │  └─ Pattern 1a: NetworkConnection + TLS
│     │     Time: 10-15 minutes
│     │
│     ├─ UDP for gaming/streaming?
│     │  └─ Pattern 1b: NetworkConnection + UDP
│     │     Time: 10-15 minutes
│     │
│     ├─ Need message boundaries (framing)?
│     │  └─ Pattern 1c: TLV Framing
│     │     Type-Length-Value for mixed message types
│     │     Time: 15-20 minutes
│     │
│     └─ Send/receive Codable objects directly?
│        └─ Pattern 1d: Coder Protocol
│           No manual JSON encoding needed
│           Time: 10-15 minutes
│
└─ iOS 12-25 or need completion handlers?
   └─ YES → NWConnection path (callbacks)
      ├─ TCP with TLS security?
      │  └─ Pattern 2a: NWConnection + TLS
      │     stateUpdateHandler, completion-based send/receive
      │     Time: 15-20 minutes
      │
      ├─ UDP streaming with batching?
      │  └─ Pattern 2b: NWConnection + UDP Batch
      │     connection.batch for 30% CPU reduction
      │     Time: 10-15 minutes
      │
      ├─ Listening for incoming connections?
      │  └─ Pattern 2c: NWListener
      │     Accept inbound connections, newConnectionHandler
      │     Time: 20-25 minutes
      │
      └─ Network discovery (Bonjour)?
         └─ Pattern 2d: NWBrowser
            Discover services on local network
            Time: 25-30 minutes

Quick selection guide

  • Gaming (low latency, some loss OK) → UDP patterns (1b or 2b)
  • Messaging (reliable, ordered) → TLS patterns (1a or 2a)
  • Mixed message types → TLV or Coder (1c or 1d)
  • Peer-to-peer → Discovery patterns (2d) + incoming (2c)

Common Patterns

Pattern 1a: NetworkConnection with TLS (iOS 26+)

Use when iOS 26+ deployment, need reliable TCP with TLS security, want async/await

Time cost 10-15 minutes

❌ BAD: Manual DNS, Blocking Socket

// WRONG — Don't do this
var hints = addrinfo(...)
getaddrinfo("www.example.com", "1029", &hints, &results)
let sock = socket(AF_INET, SOCK_STREAM, 0)
connect(sock, results.pointee.ai_addr, results.pointee.ai_addrlen) // Blocks!

✅ GOOD: NetworkConnection with Declarative Stack

import Network

// Basic connection with TLS
let connection = NetworkConnection(
    to: .hostPort(host: "www.example.com", port: 1029)
) {
    TLS() // TCP and IP inferred automatically
}

// Send and receive with async/await
public func sendAndReceiveWithTLS() async throws {
    let outgoingData = Data("Hello, world!".utf8)
    try await connection.send(outgoingData)

    let incomingData = try await connection.receive(exactly: 98).content
    print("Received data: \(incomingData)")
}

// Optional: Monitor connection state for UI updates
Task {
    for await state in connection.states {
        switch state {
        case .preparing:
            print("Establishing connection...")
        case .ready:
            print("Connected!")
        case .waiting(let error):
            print("Waiting for network: \(error)")
        case .failed(let error):
            print("Connection failed: \(error)")
        case .cancelled:
            print("Connection cancelled")
        @unknown default:
            break
        }
    }
}

Custom parameters for low data mode

let connection = NetworkConnection(
    to: .hostPort(host: "www.example.com", port: 1029),
    using: .parameters {
        TLS {
            TCP {
                IP()
                    .fragmentationEnabled(false)
            }
        }
    }
    .constrainedPathsProhibited(true) // Don't use cellular in low data mode
)

When to use

  • Secure messaging, email protocols (IMAP, SMTP)
  • Custom p

Content truncated.

axiom-swiftdata

CharlesWiltgen

Use when working with SwiftData - @Model definitions, @Query in SwiftUI, @Relationship macros, ModelContext patterns, CloudKit integration, iOS 26+ features, and Swift 6 concurrency with @MainActor — Apple's native persistence framework

11

axiom-swiftui-nav-diag

CharlesWiltgen

Use when debugging navigation not responding, unexpected pops, deep links showing wrong screen, state lost on tab switch or background, crashes in navigationDestination, or any SwiftUI navigation failure - systematic diagnostics with production crisis defense

21

axiom-ios-build

CharlesWiltgen

Use when ANY iOS build fails, test crashes, Xcode misbehaves, or environment issue occurs before debugging code. Covers build failures, compilation errors, dependency conflicts, simulator problems, environment-first diagnostics.

151

axiom-ios-vision

CharlesWiltgen

Use when implementing ANY computer vision feature - image analysis, object detection, pose detection, person segmentation, subject lifting, hand/body pose tracking.

21

axiom-haptics

CharlesWiltgen

Use when implementing haptic feedback, Core Haptics patterns, audio-haptic synchronization, or debugging haptic issues - covers UIFeedbackGenerator, CHHapticEngine, AHAP patterns, and Apple's Causality-Harmony-Utility design principles from WWDC 2021

20

axiom-in-app-purchases

CharlesWiltgen

Use when implementing in-app purchases, StoreKit 2, subscriptions, or transaction handling - testing-first workflow with .storekit configuration, StoreManager architecture, transaction verification, subscription management, and restore purchases for consumables, non-consumables, and auto-renewable subscriptions

10

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

9521,094

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

846846

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

571700

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

548492

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

673466

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

514280

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.