我正在尝试显示来自 api 的数据。当我尝试在应用程序上执行此操作时,它可以工作,但是一旦我将代码移动到小部件,它就无法在 onAppear 或按钮上工作。我需要有关如何在解码器加载时刷新 json 的帮助。我认为我的解码器需要工作我不确定是什么问题。
struct panchangWidgetEntryView : View {
@State private var panchangData: PanchangData?
var entry: Provider.Entry
var body: some View {
HStack {
Text(panchangData?.tithi ?? "")
.font(.subheadline)
.padding()
Text(panchangData?.paksha ?? "")
.font(.subheadline)
.padding()
}
}
func loadData(){
guard let url = URL(string: "API URL") else {
return
}
URLSession.shared.dataTask(with: url){ data, response, error in
guard let data = data else { return }
if let decodedData = try? JSONDecoder().decode(PanchangData.self, from: data){
DispatchQueue.main.async {
self.panchangData = decodedData
}
}
}.resume()
}
}
struct PanchangData: Decodable{
var slon: Double
var mlon: Double
var tithinum: Int
var tithi: String
var paksha: String
var tithiTill: String
var nakshatra: String
var nakshatraTill: String
var yoga: String
var yogTill: String
var karana: String
var karanTill: String
var rashi: String
var requestsremaining: Int
var requeststotal: Int
var plan: String
var status: String
var reqdate: String
var reqtime: String
}