swift-networking

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Swift Networking

Swift 网络编程

Network.framework is Apple's modern networking API for TCP/UDP connections, replacing BSD sockets with smart connection establishment, user-space networking, and seamless mobility handling.
Network.framework是Apple针对TCP/UDP连接推出的现代网络API,它以智能连接建立、用户空间网络和无缝移动性处理替代了BSD sockets。

Reference Loading Guide

参考资料加载指南

ALWAYS load reference files if there is even a small chance the content may be required. It's better to have the context than to miss a pattern or make a mistake.
ReferenceLoad When
Getting StartedSetting up NWConnection for TCP/UDP, choosing between APIs
Connection StatesHandling
.waiting
,
.ready
,
.failed
transitions
iOS 26+ NetworkingUsing NetworkConnection with async/await, TLV framing, Coder protocol
Migration GuideMoving from sockets, CFSocket, SCNetworkReachability, URLSession
TroubleshootingDebugging timeouts, TLS failures, connection issues
只要有哪怕一丝可能需要用到相关内容,就一定要加载参考文件。 提前获取上下文总好过遗漏模式或犯错。
参考资料加载场景
入门指南为TCP/UDP设置NWConnection、选择合适的API
连接状态处理
.waiting
.ready
.failed
状态切换
iOS 26+ 网络编程结合async/await使用NetworkConnection、TLV帧、Coder协议
迁移指南从sockets、CFSocket、SCNetworkReachability、URLSession迁移
故障排查调试超时、TLS故障、连接问题

Core Workflow

核心工作流程

  1. Choose transport (TCP/UDP/QUIC) based on use case
  2. Create NWConnection (iOS 12+) or NetworkConnection (iOS 26+)
  3. Set up state handler for connection lifecycle
  4. Start connection on appropriate queue
  5. Send/receive data with proper error handling
  6. Handle network transitions (WiFi to cellular)
  1. 根据使用场景选择传输协议(TCP/UDP/QUIC)
  2. 创建NWConnection(iOS 12+)或NetworkConnection(iOS 26+)
  3. 为连接生命周期设置状态处理器
  4. 在合适的队列上启动连接
  5. 通过正确的错误处理发送/接收数据
  6. 处理网络切换(WiFi切换至蜂窝网络)

When to Use Network.framework vs URLSession

何时使用Network.framework vs URLSession

  • URLSession: HTTP, HTTPS, WebSocket, simple TCP/TLS streams
  • Network.framework: UDP, custom protocols, low-level control, peer-to-peer, gaming
  • URLSession:HTTP、HTTPS、WebSocket、简单TCP/TLS流
  • Network.framework:UDP、自定义协议、底层控制、点对点通信、游戏场景

Common Mistakes

常见错误

  1. Ignoring state handlers — Creating an NWConnection without a state change handler means you never learn when it's ready or failed. Always implement the state handler first.
  2. Blocking the main thread — Never call
    receive()
    on the main queue. Use a background DispatchQueue or Task for all network operations.
  3. Wrong queue selection — Using the wrong queue (UI queue for network work, or serial queue for concurrent reads) causes deadlocks or silent failures. Always explicit your queue choice.
  4. Not handling network transitions — WiFi/cellular switches or network loss aren't always detected automatically. Implement viability checks and state monitoring for robust apps.
  5. Improper error recovery — Network errors need retry logic with backoff. Immediately failing on transient errors (timeouts, temporary loss) creates poor UX.
  1. 忽略状态处理器 —— 创建NWConnection却不设置状态变更处理器,意味着你永远无法知晓连接何时就绪或失败。一定要先实现状态处理器。
  2. 阻塞主线程 —— 绝不要在主队列上调用
    receive()
    。所有网络操作都应使用后台DispatchQueue或Task。
  3. 队列选择错误 —— 使用错误的队列(如在UI队列执行网络工作,或用串行队列处理并发读取)会导致死锁或静默失败。务必明确指定队列。
  4. 未处理网络切换 —— WiFi/蜂窝网络切换或网络中断并非总能被自动检测到。为了打造健壮的应用,需实现可用性检查和状态监控。
  5. 错误恢复不当 —— 网络错误需要带退避策略的重试逻辑。如果遇到临时错误(超时、临时断网)就直接失败,会导致糟糕的用户体验。