我WidgetCenter.shared.reloadAllTimelines()
在我的主应用程序中使用来刷新我的小部件。
该小部件包含一张图片和一个通过 json 请求获取的字符串。如果我使用上面的代码,图片会立即刷新。所以它应该是这样的。
但是字符串保持不变。它需要做另一个 json 请求。但事实并非如此。它显示了旧的字符串。为什么?使用 TimelineEntry 导入字符串。所以我想我还需要重新加载 TimelineEntry?
我怎样才能做到这一点?对于我在我看来使用的字符串entry.clubname
这是一些示例代码。我删除了一些,这样代码就不会太多了。
我的网络:
class NetworkManager: ObservableObject {
@Published var clubNameHome = "..."
init() {
fetchData() // fetch data must be called at least once
}
func fetchData() {
if let url = URL(string: "...) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (gettingInfo, response, error) in
if error == nil {
let decoder = JSONDecoder()
if let safeData = gettingInfo {
do {
let results = try decoder.decode(Results.self, from: safeData)
DispatchQueue.main.async {
self.clubNameHome = results.data[0]....
if #available(iOS 14.0, *) {
WidgetCenter.shared.reloadAllTimelines()
} else {
// Fallback on earlier versions
}
}
} catch {
print(error)
}
}
}
}
task.resume()
}
}
}
还有我的 TimelineProvider with View:
struct Provider: IntentTimelineProvider {
let networkManager = NetworkManager()
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date(), configuration: ConfigurationIntent(), clubnamehome: networkManager.clubNameHome)
}
func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {
let entry = SimpleEntry(date: Date(), configuration: configuration, clubnamehome: networkManager.clubNameHome)
completion(entry)
}
func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
var entries: [SimpleEntry] = []
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
let currentDate = Date()
let entryDate = Calendar.current.date(byAdding: .minute, value: 15, to: currentDate)!
let entry = SimpleEntry(date: entryDate, configuration: configuration, clubnamehome: networkManager.clubNameHome)
entries.append(entry)
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
struct SimpleEntry: TimelineEntry {
let date: Date
let configuration: ConfigurationIntent
let clubnamehome: String
}
struct MyTeamWidgetEntryView : View {
var entry: Provider.Entry
var body: some View {
HStack {
Spacer()
VStack (alignment: .leading, spacing: 0) {
Spacer().frame(height: 10)
HStack {
Spacer()
switch logo {
case "arminia":
Image("bundesliga1/arminia").resizable().aspectRatio(contentMode: .fit).frame(width: 90, height: 90, alignment: .center)
case "augsburg":
Image("bundesliga1/augsburg").resizable().aspectRatio(contentMode: .fit).frame(width: 90, height: 90, alignment: .center)
default:
Image("bundesliga1/bayern").resizable().aspectRatio(contentMode: .fit).frame(width: 90, height: 90, alignment: .center)
}
}
HStack{
Text(entry.clubname)
}
}
}}}