꾸준히 안타치기
tableView +Json 데이터 파싱 본문
진행순서
1. Json 데이터를 Assets에서 import해서 가져온다.(~~. json) -> json데이터 준비
2. command + N 해서 스위프트 파일을 생성 / 가져올 json형식에 맞게 struct를 만든다. (Friend.swift 생성)
Json을 사용할수 있도록 Codable을 써준다.
3 .Main.storyboard에서 ViewController를 생성한다.
4. TableView를 끌어다가 놓는다. + TableViewCell을 끌어다가 놓는다.
5. ViewController의 클래스를 생성하고 (command + N -> JsonViewController라는 클래스명으로 생성)
6. Main.storyboard에서 ViewController에 JsonViewController.swift 클래스를 연결해준다.
7. JsonViewController를 ctrl하고 클릭한뒤 tableView와 연결한다.
8. TableView를 control클릭하고 jsonViewController에 작성한 datatSource와 delegate를 끌어다 우측 노란원네모에 연결한다.
9. Friend.swift에 리턴할 내용을 작성한다. 코딩키 등..
10. JsonViewController에 Table과 셀을 등록하고, 친구를 배열로 받아온다. 테이블에 세팅해준다.
11. JsonViewController의 viewDidLoad()에 뷰가 로딩된 이후에 json디코딩하는 작업을 해주고,
tableViewReload로 데이터를 다시가져온다.
1. JSon 데이터를 Assets에서 import해서 가져온다.(~~. json) -> json데이터 준비
/*
{
"name":"하나",
"age":22,
"address_info": {
"country":"대한민국",
"city":"울산"
}
}
*/
2.command + N 해서 스위프트 파일을 생성
가져올 json형식에 맞게 struct를 만든다. (Friend.swift 생성)
json작업을위해 Codable을 추가한다.
import Foundation
struct Friend: Codable{
// address_info의 객체
struct Address: Codable {
let country: String
let city: String
}
// 이름
let name: String
// 나이
let age: Int
// 이름 바꿔주기 _안씀
// let address_info: Address
let addressInfo: Address
// 이름 + 나이를 한번에 보여주기 위해 설정
var nameAndAge: String{
return self.name + "(\(self.age))"
}
// 주소를 한방에 보여주기 위해 설정
var fullAddress: String{
return self.addressInfo.city + ", " + self.addressInfo.country
}
// 코딩 키프로토콜 설정 case에 각각의 property를 써준다.그러면 각각 매칭이 된다.
enum CodingKeys: String, CodingKey {
case name, age
case addressInfo = "address_info"
}
}
3.Main.storyboard에서 ViewController를 생성한다
4.TableView를 끌어다가 놓는다. + TableViewCell을 끌어다가 놓는다.
5. ViewController의 클래스를 생성하고 (command + N -> JsonViewController라는 클래스명으로 생성)에서 값가져오고 뷰설정
import UIKit
class JsonViewController: UIViewController, UITableViewDataSource{
// 생성한 테이블뷰 연결 하기
@IBOutlet weak var tableView: UITableView!
// 생성한 셀연결하기
let cellIdentifier: String = "cell"
// 친구리스트 가져오기
var friends: [Friend] = []
// 친구 수만큼 가져오기
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.friends.count
}
// 테이블 셀설정하는 곳
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath)
// 셀에 데이터 넣어주기
let friend : Friend = self.friends[indexPath.row]
// 친구이름 나이
// 사는 도시, 나라 가져오기
cell.textLabel?.text = friend.nameAndAge
cell.detailTextLabel?.text = friend.fullAddress
return cell
}
// 뷰가 로딩된이후에 할 것
override func viewDidLoad() {
super.viewDidLoad()
//json 디코딩하기
let jsonDecoder: JSONDecoder = JSONDecoder()
// 에셋불러오기
guard let dataAsset: NSDataAsset = NSDataAsset(name: "friends") else{
return
}
// 디코더를 이용해서 dataAsset내용 불러오기
do{
self.friends = try jsonDecoder.decode([Friend].self, from: dataAsset.data)
}catch{
print(error.localizedDescription)
}
// 테이블 데이타 다시 가져오기
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
6. Main.storyboard에서 ViewController에 JsonViewController.swift 클래스를 연결해준다.
7 .JsonViewController를 ctrl하고 클릭한뒤 tableView와 연결한다.
8. TableView를 control클릭하고 jsonViewController에 작성한 datatSourc를 끌어다 우측 노란원네모에 연결한다.
https://www.boostcourse.org/mo326/lecture/20146?isDesc=false
iOS 앱 프로그래밍
부스트코스 무료 강의
www.boostcourse.org
'iOS > Basic Study' 카테고리의 다른 글
URLSession과 URLSessionDataTask (0) | 2021.12.27 |
---|---|
OperationQueue (0) | 2021.12.26 |
Target-Action 디자인 패턴 (0) | 2021.12.21 |
Delegation이란? (0) | 2021.12.19 |
뷰의 상태변화 감지 메서드 (0) | 2021.12.19 |