Home > other >  WidgetKit - API Calls
WidgetKit - API Calls

Time:12-20

I am trying to create a widget that can display information about my car. I am currently using API for my main app, but also want to include this in my widget, but haven't found a way to do this.

How can I get value from API, and display the value in the widget? Is this even possible in WidgetKit? Should I include the API call inside the getTimeline function?

EDIT: This is the code I am using for API call:

let apii = TeslaSwift()
    
   if let jsonString = UserDefaults.standard.object(forKey: "tesla.token") as? String,
       let token: AuthToken = jsonString.decodeJSON(),
       let _ = UserDefaults.standard.object(forKey: "tesla.token") as? String {
        apii.reuse(token: token, email: nil)
    }
    
    apii.useMockServer = false
    apii.debuggingEnabled = true
    
    let id = UserDefaults(suiteName: "xxxx")!.string(forKey: "GlobalSelectedID")
    
    apii.getVehicle(id!).done {
        (vehicle: Vehicle) -> Void in
        
        apii.getAllData(vehicle).done { (extendedVehicle: VehicleExtended) in
            
            carState = (extendedVehicle.state!)
            batteryLevel = (extendedVehicle.chargeState?.batteryLevel)!
            interiorTemperature = (extendedVehicle.climateState?.insideTemperature!.celsius)!
            
            let formatter = DateFormatter()
            formatter.dateFormat = "dd.MM.yyyy - HH:mm:ss"
            let now = Date()
            let dateString = formatter.string(from:now)
            lastUpdated = dateString
            
        }.catch { (error) in
            
            print("error1: \(error)")
        }
        
    }.catch { error in
        print("error2: \(error)")
    }

CodePudding user response:

There are two ways you can display values in widgets from API.

  1. Save data in userdefaults from main app and then retrieve this data from userdefaults in getTimeLine function. You need to use app group for shared userdefaults. You can reload widgets from main app easily after saving data in userdefaults.

  2. API call from getTimeLine

  • Related