独立Apple Watch应用网络异常问题求助
问题解决:watchOS仅用应用在Series 6上网络错误-1009
问题背景
- 使用Xcode的「watch-only App」模板创建项目,在Apple Watch Series 6(watchOS 9.0)运行时,控制台输出网络错误:
ErrorDomain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." - 同一应用在Apple Watch Ultra上运行正常
- 已尝试的无效方案:
- 配置
URLSessionConfiguration的allowsCellularAccess = true和waitsForConnectivity = true - 使用Alamofire发起网络请求
- 关闭iPhone的Wi-Fi和蓝牙后,Watch Series 6可通过Wi-Fi正常请求(非用户可接受方案)
- 配置
- 关键现象:首次启动应用时,Series 6未弹出「允许应用使用无线数据」的授权请求,但Ultra会弹出
核心请求代码
VStack { Text("hello world") } .onAppear { guard let url = URL(string: "https://api.thecatapi.com/v1/images/search?limit=1") else { print("Invalid URL") self.error = "Invalid URL" return } let dataTask = URLSession.shared.dataTask(with: url) {(data, response, error) in guard error == nil else { print(error) return } print(data) } dataTask.resume() }
解决方案
1. 手动添加网络权限描述到Watch App的Info.plist
watchOS 9部分机型可能不会自动触发权限弹窗,需手动在Watch App的Info.plist中添加权限描述:
- 右键
Info.plist→ 「Open As」→ 「Source Code」 - 添加以下代码:
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <false/> <key>NSExceptionDomains</key> <dict> <key>api.thecatapi.com</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSAllowsArbitraryLoads</key> <true/> </dict> </dict> </key> <key>NSNetworkUsageDescription</key> <string>需要网络权限获取猫咪图片</string>
注意:
NSNetworkUsageDescription必须填写明确的用途描述,否则可能导致权限不生效
2. 重置Watch的网络权限设置
如果手动添加描述后仍未弹出授权弹窗,可尝试重置网络权限:
- 在iPhone的「Watch」App中,进入「通用」→ 「还原」→ 「还原网络设置」
- 重启Watch和iPhone后重新安装应用
3. 自定义URLSession配置并强制触发权限检查
避免使用URLSession.shared,自定义配置并显式设置网络参数,确保系统检测到网络请求需求:
VStack { Text("hello world") } .onAppear { let config = URLSessionConfiguration.default config.allowsCellularAccess = true config.waitsForConnectivity = true let session = URLSession(configuration: config) guard let url = URL(string: "https://api.thecatapi.com/v1/images/search?limit=1") else { print("Invalid URL") self.error = "Invalid URL" return } let dataTask = session.dataTask(with: url) {(data, response, error) in guard error == nil else { print(error) return } print(data) } dataTask.resume() }
4. 检查Watch与iPhone的配对网络状态
当Watch与iPhone配对时,默认通过iPhone的网络请求,需确保:
- iPhone的蜂窝数据或Wi-Fi处于正常连接状态
- iPhone的「设置」→「蜂窝网络」中,找到对应Watch应用,确认「无线数据」权限已开启
内容的提问来源于stack exchange,提问作者jiaoxiaker abby
相关产品推荐
相关产品推荐

