iOS&Swift🍎

IOS JSON 데이터 받아오기

천 원 2022. 3. 23. 04:39

먼저 받아 오려는 JSON데이터 부터 확인후 그에 맞게 구조체를 만들어준다!

여기서 temp를 받아오고 싶다면! 요로코롬 구조체 만들어 주고

struct Data: Decodable{
	let main: Main
}

struct Main: Decodable{
	let temp: Double
}

그 후에

let decoder = JSONDecoder()
do{
	let decodedData = try decoder.decode(Data.self, from: data) // data에 URLSession으로 받아온 data 넣어준다!
	print(decodedData.main.temp) // 출력!
} catch{
	print(error)
}