RESTful API 의 기본인 JSON데이터를 Swift의 Codable을 사용해 파싱해보자!
먼저 초기 JSON과 UI를 대략 그려본다.
{
"name": "이기회",
"age": 77,
"picture": "sample",
"isActive": true,
}
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "person")
.resizable()
.frame(width: 150, height: 150)
.clipShape(Circle())
.overlay(Circle().stroke(.gray, lineWidth: 4))
Text("Name")
Text("Age")
}
}
}
이제 위의 UI에서 Image에 Json데이터의 picture를 넣어주고
Name에 이름, Age에 나이를 데이터를 넣어주어야 하는데 그 작업에 앞서 JSON을 Data로 파싱하는 작업이 필요하다.
JSON 파싱하기
먼저 JSON데이터에 맞춰서 codable을 준수하는 모델 struct를 만들어준다.
let testJson1 = """
{
"name": "이기회",
"age": 77,
"picture": "sample",
"isActive": true,
}
"""
struct User: Codable {
let name: String
let age: Int
let picture: String
let isActive: Bool
}
앞서 만든 UI가 onAppear될 때 json을 파싱한다.
VStack {
Image(systemName: "person")
.resizable()
.frame(width: 150, height: 150)
.clipShape(Circle())
.overlay(Circle().stroke(.gray, lineWidth: 4))
Text("Name")
Text("Age")
}
// 여기 추가
.onAppear {
// json을 파싱한다.
let jsonData = testJson1.data(using: .utf8)
do {
guard let jsonData = jsonData else { return }
let data = try JSONDecoder().decode(User.self, from: jsonData)
print("파싱 성공: \(data)")
} catch {
print("error: \(error)")
}
}
이후 시뮬레이터를 빌드 후 실행하고 아래와 같은 로그가 나온다면 파싱은 성공한 것이다!!
이제 이 데이터를 가지고 UI에 그려주면 된다.
UI에 데이터 뿌려주기
먼저 Asset에 sample이라는 이름의 이미지파일을 하나 추가해준다.
struct ContentView: View {
// UI를 변경하기 위해 @State를 사용
@State private var user: User = User(name: "", age: 0, picture: "", isActive: true)
var body: some View {
VStack {
Image(user.picture) // picture
.resizable()
.frame(width: 150, height: 150)
.clipShape(Circle())
.overlay(Circle().stroke(user.isActive ? .green : .gray, lineWidth: 4)) // isActive에 따라 색 변경하기
Text(user.name) // name
Text("\(user.age)") // age
}
.onAppear {
// json을 파싱한다.
let jsonData = testJson1.data(using: .utf8)
do {
guard let jsonData = jsonData else { return }
let data = try JSONDecoder().decode(User.self, from: jsonData)
print("파싱 성공: \(data)")
user = data // 파싱 성공한 데이터를 user에 넣기
} catch {
print("error: \(error)")
}
}
}
}
(주석 처리한 부분만 변경해주면 된다.)
이제 시뮬레이터를 돌려보면 위와 같이 데이터를 불러온 화면을 확인 할 수 있다.
'iOS > SwiftUI' 카테고리의 다른 글
SwiftUI와 상태관리 (0) | 2022.04.03 |
---|---|
SwiftUI에서 스켈레톤 UI 적용하기 (0) | 2022.02.20 |
[SwiftUI] EnvironmentObject / ObservedObject / StateObject (0) | 2022.01.30 |
[Swift] Codable로 JSON파싱하기 -확장- (0) | 2022.01.30 |
[SwiftUI] PencilKit을 사용해 캔버스 만들기 (0) | 2022.01.15 |