본문 바로가기
iOS

[iOS] JSON 파싱

by thoonk: 2020. 12. 4.

JSON 파싱하는 방법에 대해서 적어보겠습니다..!

 

우선 서버에 요청할 Request함수가 필요합니다. 아래 주석의 순서대로 함수를 만들어 줍니다.

func performRequest(with urlString: String) {
    // 1. URL 만들기
    if let url  = URL(string: urlString) {
        // 2. URLSession 만들기
        let session = URLSession(configuration: .default)
        // 3. session에 task 할당
        let task = session.dataTask(with: url) { (data, response, error) in
            if error != nil {
                self.delegate?.didFailWithError(error!)
                // exit out of this function
                return
            }
                
            if let safeData = data {
                if let weather = self.parseJSON(safeData) {                        
                    // 클로저 안에서 바깥 변수 사용시 self 붙이기
                    self.delegate?.didUpdateWeather(self, weather: weather)
                }
            }
        }
        // 4. task 시작
        task.resume()
    }
}

그리고 parseJSON 함수를 만들어 줍니다.

서버로부터 받은 데이터를 JSONDecoder 클래스를 이용해서 미리 만들어 놓은 Codable(Decodable & Encodable)을 준수하는 WeatherData타입으로 디코딩해줍니다.

func parseJSON(_ weatherData: Data) -> WeatherModel? {
    let decoder = JSONDecoder()
    do {
        let decodedData = try! decoder.decode(WeatherData.self, from: weatherData)
        let id = decodedData.weather[0].id
        let temp = decodedData.main.temp
        let name = decodedData.name
            
        let weather = WeatherModel(conditionId: id, cityName: name, temperature: temp)
        return weather
            
    } catch {
        delegate?.didFailWithError(error)
        return nil
    }
}

 

자세한 코드는 ↓

https://github.com/thoonk/Udemy-iOS-Prjoect/tree/main/Clima

 

thoonk/Udemy-iOS-Prjoect

iOS 13 & Swift 5 - The Complete iOS App Development Bootcamp by Dr.Angela Yu - thoonk/Udemy-iOS-Prjoect

github.com

 

'iOS' 카테고리의 다른 글

[iOS] Frame과 Bounds의 차이  (0) 2021.01.12
[iOS] UNUserNotificationCenter를 이용해서 로컬 푸시하기!  (1) 2021.01.05
[iOS] User Notification  (1) 2020.12.29
[iOS] Label에 취소선 긋기  (1) 2020.12.24
[iOS] Dispatch Queue  (0) 2020.11.23

댓글