[ad_1]
I’m making an attempt to make a view that exhibits the stats of a bulb, I wish to present if the system is on or off and what its brightness is. I have already got an API that may return this info in JSON and still have an internet GUI. However I wish to make an app on my iPhone so I’m very new to Swift so used this video to parse the JSON response from the API and print it to the console. I now do not know the right way to really put the data I get into seen items of textual content. I’ll present you the JSON return I get and the code I’ve already executed:
Parsed JSON
BulbInfo(error_code: 0, end result: UITest.Outcome(device_on: true, brightness: 100))
API return JSON
{'error_code': 0,
'end result': {
'device_id': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'fw_ver': '1.1.9 Construct 20210122 Rel. 56165',
'hw_ver': '1.0.0',
'sort': 'SMART.TAPOBULB',
'mannequin': 'L510 Sequence',
'mac': 'xx-xx-xx-xx-xx-xx',
'hw_id': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'fw_id': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'oem_id': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'specs': 'EU',
'lang': 'en_US',
'device_on': True,
'on_time': 3065,
'overheated': False,
'nickname': 'TWFpbiBMaWdodA==',
'avatar': 'hang_lamp_1',
'brightness': 100,
'default_states': {
'brightness': {
'sort': 'last_states',
'worth': 100
}
},
'time_diff': 0,
'area': 'Europe/London',
'longitude': -xxxxx,
'latitude': xxxxxx,
'has_set_location_info': True,
'ip': '192.168.x.xxx',
'ssid': 'xxxxxxxxxxxx',
'signal_level': 1,
'rssi': -xx
}
}
ContentView.swift
import SwiftUI
struct ContentView: View {
func getDeviceInfo(){
let urlString = "http://192.168.x.xxx:xxx/get_bulb_info"
let url = URL(string:urlString)
let session = URLSession.shared
let dataTask = session.dataTask(with: url!){(information,response,error)in
// Test for error
if error == nil && information != nil {
// Parse JSON
let decoder = JSONDecoder()
do{
let bulbInfo = strive decoder.decode(BulbInfo.self, from: information!)
print(bulbInfo)
}
catch{
print(error)
}
}
}
dataTask.resume()
}
var physique: some View {
Textual content("Fundamental Gentle:").padding()
Button(motion:getDeviceInfo){
Textual content("Get Machine Information!")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Bulb.swift
//
// Bulb.swift
// UITest
//
// Created by James Westhead on 18/12/2021.
//
import Basis
struct BulbInfo: Codable{
var error_code: Int
var end result: Outcome
}
struct Outcome: Codable{
var device_on:Bool
var brightness: Int
}
[ad_2]
