You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Swift现代并发(AsyncStream)实现NWPathMonitor并启动监控?

解决NWPathMonitor结合AsyncStream的监控启动问题

你的代码核心问题是没有调用monitor.start(queue:)方法,所以网络路径监控根本没启动。下面是修正后的扩展实现,完美适配Swift现代并发:

extension NWPathMonitor {
    static var networkPath: AsyncStream<NWPath> {
        AsyncStream { continuation in
            let monitor = NWPathMonitor()
            let queue = DispatchQueue(label: "com.yourdomain.networkmonitor", qos: .utility)
            
            monitor.pathUpdateHandler = { path in
                continuation.yield(path)
            }
            
            continuation.onTermination = { @Sendable _ in
                monitor.cancel()
            }
            
            // 启动监控,传入专用队列
            monitor.start(queue: queue)
        }
    }
}

关键说明:

  • 必须创建一个专用的DispatchQueue传入start(queue:),不能用主队列(避免阻塞UI),推荐用.utility服务质量等级,适合后台监控任务。
  • AsyncStream的生命周期和监控绑定:当流终止时(比如for await循环结束),onTermination会自动调用monitor.cancel()清理资源,避免内存泄漏。
  • 使用示例:
Task {
    for await path in NWPathMonitor.networkPath {
        print("当前网络状态:\(path.status.rawValue)")
        print("是否使用蜂窝网络:\(path.isExpensive)")
    }
}

内容的提问来源于stack exchange,提问作者logicito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 16:01:08