33일차 - 21.07.10

수킴·2021년 7월 12일
0

100DaysOfSwift

목록 보기
34/37
post-thumbnail

학습키워드

  • UITabBarController
  • Data
  • Codable

1. Setting up

  • 프로젝트 개요
    • 인터넷에서 데이터를 가져와 사용자에게 표시하는 프로젝트
    • UITabBarController 를 사용하여 옵션을 선택합니다.

2. Creating the basic UI: UITabBarController

tab bar 를 사용하면 사용자가 관심있는 항목을 탭하여 보고 싶은 화면을 제어할 수 있습니다.

  • Editor > Embed In > Tab Bar Controller - 탭바컨트롤러 래핑
  • Editor > Embed In > Navigation Controller - 네비게이션컨트롤러 래핑

UITabBarItem

  • 시스템 항목 설정할 때 SystemItem을 커스텀속성 및 여러가지 속성을 제공합니다.
  • 텍스트를 직접 설정하는 경우 아이콘이 제거되고 직접 제공해야 합니다.

Cell스타일이 Subtitle 인경우 textLabel.textdetailTextLabel.text 로 텍스트를 설정할 수 있습니다.

3. Parsing JSON using the Codable protocol

Codable 프로토콜을 채택하면 문자열, 딕셔너리 또는 구조체와 같은 스위프트 데이터를 인터넷을 통해 전송할 수 있는 데이터로 변환할 수 있습니다.

데이터가 Codable 을 준수한다고 하면 해당 데이터와 JSON간에 자유롭게 변환할 수 있습니다,

JSON (JavaScript Object Notation) 데이터를 설명하는 방법입니다. 컴퓨터용으로 분석하기 쉽기 때문에 대역폭이 중요한 온라인에서 자주 사용됩니다.

JSON 모델 작성

{
    "metadata":{
        "responseInfo":{
            "status":200,
            "developerMessage":"OK",
        }
    },
    "results":[
        {
            "title":"Legal immigrants should get freedom before undocumented immigrants – moral, just and fair",
            "body":"I am petitioning President Trump's Administration to take a humane view of the plight of legal immigrants. Specifically, legal immigrants in Employment Based (EB) category. I believe, such immigrants were short changed in the recently announced reforms via Executive Action (EA), which was otherwise long due and a welcome announcement.",
            "issues":[
                {
                    "id":"28",
                    "name":"Human Rights"
                },
                {
                    "id":"29",
                    "name":"Immigration"
                }
            ],
            "signatureThreshold":100000,
            "signatureCount":267,
            "signaturesNeeded":99733,
        },
        {
            "title":"National database for police shootings.",
            "body":"There is no reliable national data on how many people are shot by police officers each year. In signing this petition, I am urging the President to bring an end to this absence of visibility by creating a federally controlled, publicly accessible database of officer-involved shootings.",
            "issues":[
                {
                    "id":"28",
                    "name":"Human Rights"
                }
            ],
            "signatureThreshold":100000,
            "signatureCount":17453,
            "signaturesNeeded":82547,
        }
    ]
}
  1. 메타데이터 값이 있으며 responseInfo 에는 상태값이 포함됩니다. 200상태코드는 정상적인 상태를 의미합니다.
  2. results 배열안에 각각의 항목의 값들이 있습니다.
  3. 각 항목에는 제목, 본문, 관련된 문제 및 서명 정보가 포함되어 있습니다.
  4. JSON 에서는 정수는 따옴표를 감싸지 않습니다.

💡 JSON모델을 구조체로 작성하면 memberwise initializer를 제공하기 때문에 편리합니다.

데이터 다운로드

override func viewDidLoad() {
    super.viewDidLoad()

    // let urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100"
    let urlString = "https://www.hackingwithswift.com/samples/petitions-1.json"

    if let url = URL(string: urlString) {
        if let data = try? Data(contentsOf: url) {
            // we're OK to parse!
        }
    }
}
  • urlString → 서버 또는 데이터를 가지고 있는 주소에 접근합니다.
  • url이 유효한 경우 Data객체를 생성합니다.
  • 이 코드는 인터넷에서 데이터를 다운로드하는 동안 메인스레드에서 작동하기 때문에 모든 데이터가 전송될 때까지 다른 작업을 할 수 없습니다.

JSON 파싱

func parse(json: Data) {
    let decoder = JSONDecoder()

    if let jsonPetitions = try? decoder.decode(Petitions.self, from: json) {
        petitions = jsonPetitions.results
        tableView.reloadData()
    }
}
  • JSONDecoder : JSON과 Codable객체간의 변환부분을 맡습니다.
  • decode() 메서드를 사용하여 변환하도록 요청합니다.

링크

100 Days of Swift - Day 33 - Hacking with Swift

profile
iOS 공부 중 🧑🏻‍💻

0개의 댓글