WidgetKit中无法调用简单API的问题求助
WidgetKit组件网络请求失败的解决方法
问题场景
在WidgetKit组件中调用https://jsonplaceholder.typicode.com/posts/1接口时持续失败,返回DNS解析错误,但该接口在主应用、JavaScript脚本及cURL命令中均可正常访问。
实现代码
import WidgetKit import SwiftUI struct Post: Decodable { let title: String } struct Provider: AppIntentTimelineProvider { func placeholder(in context: Context) -> SimpleEntry { SimpleEntry(date: Date(), title: "Loading...", configuration: ConfigurationAppIntent()) } func snapshot(for configuration: ConfigurationAppIntent, in context: Context) async -> SimpleEntry { SimpleEntry(date: Date(), title: "Preview Title", configuration: configuration) } func timeline(for configuration: ConfigurationAppIntent, in context: Context) async -> Timeline<SimpleEntry> { var entries: [SimpleEntry] = [] let currentDate = Date() let title = await fetchPostTitle() ?? "Failed to load title" for hourOffset in 0..<5 { let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)! let entry = SimpleEntry(date: entryDate, title: title, configuration: configuration) entries.append(entry) } return Timeline(entries: entries, policy: .atEnd) } private func fetchPostTitle() async -> String? { let url = URL(string: "https://jsonplaceholder.typicode.com/posts/1")! do { let (data, _) = try await URLSession.shared.data(from: url) let post = try JSONDecoder().decode(Post.self, from: data) return post.title } catch { print("Error fetching post: \(error)") return nil } } } struct SimpleEntry: TimelineEntry { let date: Date let title: String let configuration: ConfigurationAppIntent } struct PostWidgetEntryView : View { var entry: Provider.Entry var body: some View { VStack { Text("Post Title:") Text(entry.title) .font(.headline) .multilineTextAlignment(.center) .padding() Text("Time:") Text(entry.date, style: .time) .font(.footnote) } } } struct PostWidget: Widget { let kind: String = "PostWidget" var body: some WidgetConfiguration { AppIntentConfiguration(kind: kind, intent: ConfigurationAppIntent.self, provider: Provider()) { entry in PostWidgetEntryView(entry: entry) .containerBackground(.fill.tertiary, for: .widget) } } }
错误信息(中文翻译)
networkd_settings_read_from_file 沙箱阻止此进程读取位于"/Library/Preferences/com.apple.networkd.plist"的networkd设置文件,请添加例外。 此进程的沙箱配置文件阻止与网络内容过滤器通信,请修改沙箱配置文件以允许访问com.apple.nesessionmanager.content-filter Mach服务 nw_resolver_can_use_dns_xpc_block_invoke 沙箱不允许访问com.apple.dnssd.service服务 nw_resolver_create_dns_service_locked [C1.1] DNSServiceCreateDelegateConnection失败: ServiceNotRunning(-65563) 连接1: 收到失败通知 连接1: 连接失败 10:-72000, 原因-1 连接1: 遇到错误(10:-72000) 任务 <32EC2820-3C35-4D72-BDD6-541D73FFE25E>.<1> HTTP加载失败, 0/0字节 (错误码: -1003 [10:-72000]) 任务 <32EC2820-3C35-4D72-BDD6-541D73FFE25E>.<1> 执行结束,错误[-1003] Error Domain=NSURLErrorDomain Code=-1003 "无法找到指定主机名的服务器。" UserInfo={_kCFStreamErrorCodeKey=-72000, NSUnderlyingError=0x12f606760 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorDomainKey=10, _kCFStreamErrorCodeKey=-72000, _NSURLErrorNWResolutionReportKey=在1ms内解析了0个端点,使用未知查询方式, _NSURLErrorNWPathKey=satisfied (路径已满足), 接口: en0[802.11], ipv4, dns, 使用wifi}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <32EC2820-3C35-4D72-BDD6-541D73FFE25E>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <32EC2820-3C35-4D72-BDD6-541D73FFE25E>.<1>" ), NSLocalizedDescription=无法找到指定主机名的服务器。, NSErrorFailingURLStringKey=https://jsonplaceholder.typicode.com/posts/1, NSErrorFailingURLKey=https://jsonplaceholder.typicode.com/posts/1, _kCFStreamErrorDomainKey=10} nw_resolver_create_dns_service_locked [C2.1] DNSServiceCreateDelegateConnection失败: ServiceNotRunning(-65563) 连接2: 收到失败通知 连接2: 连接失败 10:-72000, 原因-1 连接2: 遇到错误(10:-72000) 任务 <69DF6341-40DA-4519-B132-F827D665243F>.<2> HTTP加载失败, 0/0字节 (错误码: -1003 [10:-72000]) 任务 <69DF6341-40DA-4519-B132-F827D665243F>.<2> 执行结束,错误[-1003] Error Domain=NSURLErrorDomain Code=-1003 "无法找到指定主机名的服务器。" UserInfo={_kCFStreamErrorCodeKey=-72000, NSUnderlyingError=0x140822a20 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorDomainKey=10, _kCFStreamErrorCodeKey=-72000, _NSURLErrorNWResolutionReportKey=在0ms内解析了0个端点,使用未知查询方式, _NSURLErrorNWPathKey=satisfied (路径已满足), 接口: en0[802.11], ipv4, dns, 使用wifi}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDownloadTask <69DF6341-40DA-4519-B132-F827D665243F>.<2>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDownloadTask <69DF6341-40DA-4519-B132-F827D665243F>.<2>" ), NSLocalizedDescription=无法找到指定主机名的服务器。, NSErrorFailingURLStringKey=https://jsonplaceholder.typicode.com/posts/1, NSErrorFailingURLKey=https://jsonplaceholder.typicode.com/posts/1, _kCFStreamErrorDomainKey=10} [S:1] 收到错误: 连接已失效。
解决步骤
问题根源在于Widget扩展的沙箱权限未配置网络出站权限,按以下步骤修复:
- 在Xcode中选中Widget对应的target(注意不是主应用target)
- 切换到Signing & Capabilities标签页
- 找到App Sandbox权限配置项,确保勾选了**Outgoing Connections (Client)**选项
- 重新运行Widget组件
完成以上操作后,Widget即可正常发起网络请求并解析API返回的数据。
内容的提问来源于stack exchange,提问作者bartzalewski
相关产品推荐
相关产品推荐

