I can’t fetch a simple API in WidgetKit. I want to fetch data in a widget from an API: https://jsonplaceholder.typicode.com/posts/1. It doesn’t work. I tried it in Swift apps, JavaScript, and cURL, and it works perfectly everywhere except in the WidgetKit environment. I can’t fetch a simple API in WidgetKit. Specifically, I want to retrieve data from the API: https://jsonplaceholder.typicode.com/posts/1
. However, it doesn’t work in the widget.
Here’s my code:
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)
}
}
}
Here are the errors I get:
networkd_settings_read_from_file Sandbox is preventing this process from reading networkd settings file at "/Library/Preferences/com.apple.networkd.plist", please add an exception.
The sandbox profile for this process is preventing communication with network content filters. Please modify the sandbox profile to allow access to the com.apple.nesessionmanager.content-filter Mach service
nw_resolver_can_use_dns_xpc_block_invoke Sandbox does not allow access to com.apple.dnssd.service
nw_resolver_create_dns_service_locked [C1.1] DNSServiceCreateDelegateConnection failed: ServiceNotRunning(-65563)
Connection 1: received failure notification
Connection 1: failed to connect 10:-72000, reason -1
Connection 1: encountered error(10:-72000)
Task <32EC2820-3C35-4D72-BDD6-541D73FFE25E>.<1> HTTP load failed, 0/0 bytes (error code: -1003 [10:-72000])
Task <32EC2820-3C35-4D72-BDD6-541D73FFE25E>.<1> finished with error [-1003] Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo={_kCFStreamErrorCodeKey=-72000, NSUnderlyingError=0x12f606760 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorDomainKey=10, _kCFStreamErrorCodeKey=-72000, _NSURLErrorNWResolutionReportKey=Resolved 0 endpoints in 1ms using unknown from query, _NSURLErrorNWPathKey=satisfied (Path is satisfied), interface: en0[802.11], ipv4, dns, uses wifi}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <32EC2820-3C35-4D72-BDD6-541D73FFE25E>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <32EC2820-3C35-4D72-BDD6-541D73FFE25E>.<1>"
), NSLocalizedDescription=A server with the specified hostname could not be found., 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 failed: ServiceNotRunning(-65563)
Connection 2: received failure notification
Connection 2: failed to connect 10:-72000, reason -1
Connection 2: encountered error(10:-72000)
Task <69DF6341-40DA-4519-B132-F827D665243F>.<2> HTTP load failed, 0/0 bytes (error code: -1003 [10:-72000])
Task <69DF6341-40DA-4519-B132-F827D665243F>.<2> finished with error [-1003] Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo={_kCFStreamErrorCodeKey=-72000, NSUnderlyingError=0x140822a20 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorDomainKey=10, _kCFStreamErrorCodeKey=-72000, _NSURLErrorNWResolutionReportKey=Resolved 0 endpoints in 0ms using unknown from query, _NSURLErrorNWPathKey=satisfied (Path is satisfied), interface: en0[802.11], ipv4, dns, uses wifi}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDownloadTask <69DF6341-40DA-4519-B132-F827D665243F>.<2>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDownloadTask <69DF6341-40DA-4519-B132-F827D665243F>.<2>"
), NSLocalizedDescription=A server with the specified hostname could not be found., NSErrorFailingURLStringKey=https://jsonplaceholder.typicode.com/posts/1, NSErrorFailingURLKey=https://jsonplaceholder.typicode.com/posts/1, _kCFStreamErrorDomainKey=10}
[S:1] Error received: Connection invalidated.
Tried in Swift apps, JavaScript, and cURL – works everywhere except in the widget.