【问题标题】:How do I make my widget update more frequently or update when an action happens within the app如何使我的小部件更新更频繁或在应用内发生操作时更新
【发布时间】:2021-08-05 20:56:44
【问题描述】:

我有一个从我的应用程序中获取数据的小部件。该小部件工作正常,但更新不够频繁。理想情况下,我喜欢在我的应用程序中删除或添加项目时更新它,因此如果有一种方法可以强制小部件更新,那就可以了。否则,如果小部件可以更频繁地获取新数据,那么它也可以正常工作。

数据存储在应用组中的 json 文件中。我将该数据加载并解码到一个数组中,然后从该数组中选择一个随机项进行显示。

这是小部件提供程序:

let testBook = Book(id: UUID(), name: "Name", author: "Author", genre: "Error", page: "0", total: "77")

public enum AppGroup: String {
  case Livre = "group.com.identifier"

  public var containerURL: URL {
    switch self {
    case .Livre:
      return FileManager.default.containerURL(
      forSecurityApplicationGroupIdentifier: self.rawValue)!
    }
  }
}

struct Provider: TimelineProvider {
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date(), book: testBook)
    }

    func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), book: testBook)
        completion(entry)
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        var entries: [SimpleEntry] = []
            
        let currentDate = Date()
        for hourOffset in 0 ..< 5 {
            let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
            let books: [Book] = self.load("list")
            let entry = SimpleEntry(date: entryDate, book: books.randomElement() ?? testBook)
            entries.append(entry)
        }
            
        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
        
    
    }
    
    func load<T: Decodable>(_ filename: String) -> T {
        let groupDirectory = AppGroup.Livre.containerURL
        let groupURL = groupDirectory
            .appendingPathComponent(filename)
            .appendingPathExtension("json")

        return try! JSONDecoder().decode(T.self, from: Data(contentsOf: groupURL))
    }
}

由于我是 widgetKit 新手,我不确定我是否提供了足够的上下文,如果您需要更多信息或代码,请告诉我。

【问题讨论】:

    标签: ios json swift swiftui widgetkit


    【解决方案1】:

    您始终可以使用下面的代码块从您的应用中更新您的小部件。请注意,您需要 import WidgetKit 到您的班级才能调用此函数。

    WidgetCenter.shared.reloadAllTimelines()
    

    【讨论】:

    • 另外,如果您有多个小部件并且只想重新加载特定的小部件,请使用WidgetCenter.shared.reloadTimelines(ofKind: "com.mygame.gamestatus")
    猜你喜欢
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 2022-11-04
    相关资源
    最近更新 更多