我的应用程序中有一个类似于基本天气小部件的小部件。
我想在不让用户注意到的情况下刷新小部件的内容。
并且根据 Apple 文档 go to Updating Content 他们说:
To help your widget look up to date, the system occasionally captures snapshots of your widget’s view. When the widget becomes visible again, the most recent snapshot is displayed until the system replaces it with a live version of the view. To update a widget’s state before a snapshot is taken, be sure to conform to the NCWidgetProviding protocol.
所以我使用widgetPerformUpdate 来更新我的小部件内容
但发生的事情是应用程序显示来自 MainInterface.storboard 的“初始设计”,直到获取数据并更新屏幕,每次我向左向右滑动时,我都会获得“初始设计”,直到获得数据!
我的代码是:
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
getWeatherInfo()
completionHandler(NCUpdateResult.newData)
}
有人知道问题是什么以及如何解决吗?
谢谢。
最佳答案
你应该等待,先获取weatherInfo
,然后在widgetPerformUpdate
中启动completionHandler
,我会在中添加一个完成 block >getWeatherInfo()
方法并按如下方式执行:
为 getWeatherInfo 方法添加一个 completionHandler
func getWeatherInfo(completion: (_ result: Bool) -> Void)
然后当你在 getWeatherInfo
方法中完成获取天气时调用完成 block ,在这里你可以指定新的天气数据是否可用,所以你可以做
completion(true)
如果成功接收到天气,然后您只需像这样重写 widgetPerformUpdate
:
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
getWeatherInfo { didUpdate in
completionHandler(.newData)
//you can check didUpdate and if it is false return .noData
}
}
关于ios - 通过 widgetPerformUpdate 刷新 Today Extension 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951806/