gpt4 book ai didi

ios - 保持电池 iOS WidgetKit 更新

转载 作者:行者123 更新时间:2023-12-05 06:57:43 25 4
gpt4 key购买 nike

我正在开发电池 WidgetKit ,但在更新电池电量时遇到问题经常够了。每次电池百分比变化时,我都希望更新 WidgetKit 。但是从我所做的所有阅读来看,这似乎是不可能的。我尝试每 5 分钟和每 15 分钟请求一个新的时间线,但没有成功。我在 AppStore 上看到一些应用程序有电池指示器,而且它经常更新。任何线索让他们完成这个?我看到有人在谈论使用后台获取。这不是最好的方法吗?我已经包含了我的代码,也许我实现错了?感谢对此的任何反馈!

提供者

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

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

func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
let currentDate = Date()
let newDate = Calendar.current.date(byAdding: .minute, value: 15, to: currentDate)

let timeline = Timeline(entries: [SimpleEntry(date: currentDate)], policy: .after(newDate!))
completion(timeline)
}
}

BatteryWidgetEntryView

struct BatteryWidgetEntryView : View {
var entry: Provider.Entry

var body: some View {
Text("\(Int(Self.battery * 100))")
.font(.largeTitle)
}

static let battery: Float = {
UIDevice.current.isBatteryMonitoringEnabled = true
let batteryLvl = UIDevice.current.batteryLevel
return batteryLvl
}()
}

最佳答案

您不能从 WidgetKit 中执行此操作,您必须从主机应用程序重新加载时间线。主机app监控电池状态和通话

WidgetCenter.shared.reloadTimelines(ofKind: "com.mybattery.widget")

触发 WidgetKit 的重新加载。

关于ios - 保持电池 iOS WidgetKit 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64850630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com