상세 컨텐츠

본문 제목

[iOS] URLsession으로 통신하기 3탄

SWIFT

by 옹홍 2021. 4. 28. 12:48

본문

URLsession으로 통신하기 3탄에서는 JSON파일인 데이터에서 어떻게 데이터를 빼와서 앱에서 사용할 수 있는지 공부해보는 주제이다.

api에서 json 파일을 보면 이렇게 생겼다. 물론 이것은 크롬에서 json Viewer을 깔아서 더 이쁘게 보이는 것이다. 원래는 더 보기 어렵게 생겼다.

우리는 이것을 이렇게 받은 데이터를 어떻게 데리고 와야할까? 라는 고민이 생긴다. 그때 우리가 써야하는것은 여기 아래 있는 parseJSON 함수이다. 즉 JSON 디코딩하는 방법이다.

우리는 json파일을 jsondecoder를 사용해서 데이터를 가지고 올 수 있다. 이때 우리가 필요한것은, WeatherModel과 weatherData가 필요하다. 

<func parseJSON>

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

decode메서드에는 두개의 파라미터가 필요합니다. 첫 파리미터는 디코딩할 타입을 정의해야합니다. 디코딩할 타입은 위의 코드에서는 weatherdata입니다. 두번째 파라미터는, json이 저장되어있는 data를 전달해야합니다.. 그렇다면 weatherData가 어떻게 생겨먹었는지 볼 필요가 있습니다.

struct WeatherData: Codable {
    let name: String
    let main: Main
    let weather: [Weather]
    let coord: Coord
}

struct Main: Codable {
    let temp: Double
}

struct Weather: Codable {
    let description: String
    let id: Int
}

struct Coord: Codable {
    let lon: CLLocationDegrees
    let lat: CLLocationDegrees
}

<WeatherData>

weatherData구조체를 보면, codable이라는 프로토콜이 채택되어있습니다. codable이라는 프로토콜을 통해서 decode된 json 파일의 데이터가 저장 수 있는거죠!! 

그리고 위에 parseJSON함수는 weatherModel을 반환하는데요! 이는 jsonDecoder로 디코딩한 모든 데이터를 한번에 묶어서 보내기 위한 것입니다. 그렇다면 weatherModel은 어떻게 생겼냐면?

struct WeatherModel {
    let conditionId: Int
    let cityName: String
    let temperature: Double
    let coordinate: (CLLocationDegrees, CLLocationDegrees)
    
    var temperatureString: String {
        return String(format: "%.1f", temperature)
    }
    
    var conditionName: String {
        switch conditionId {
        case 200...232:
            return "cloud.bolt.rain"
        case 300...321:
            return "cloud.drizzle"
        case 500...531:
            return "cloud.rain"
        case 600...622:
            return "cloud.snow"
        case 701...781:
            return "cloud.fog"
        case 800:
            return "sun.max"
        case 801...804:
            return "cloud"
        default:
            return "cloud"
        }
    }
}

이렇게 생겼습니다!!  결국 보면, jsondecoder로 디코딩한 데이터를  각 변수에 담고, weathermodel의 init으로 데이터를 weathermodel에 저장한 뒤에 다시 이를 방출하는 것입니다. 그리고는 delegate 패턴으로 viewcontroller로 데이터를 전달하게 되죠!!

 

 

관련글 더보기

댓글 영역