[TIL] 10.05

Junyoung_Hong·2023년 10월 5일
0

TIL_10월

목록 보기
3/20
post-thumbnail

1. SwiftyJSON

SwiftyJSON은 JSON형태의 데이터를 쉽게 파싱하여 사용할 수 있게 해주는 라이브러리이다.

1-1. JSON 데이터 생성

우선 JSON 데이터를 생성하자.

import SwiftyJSON

let json = JSON(["name": "Junyoung", "age": 26])

1-2. JSON 데이터 파싱

SwiftyJSON을 사용해서 JSON 데이터를 파싱할 수 있다.

import SwiftyJSON

let jsonString = "{\"name\": \"Junyoung\", \"age\": 26}"
if let jsonData = jsonString.data(using: .utf8) {
    let json = try? JSON(data: jsonData)
    
    // JSON 데이터에서 값을 추출할 수 있다.
    let name = json?["name"].stringValue
    let age = json?["age"].intValue
    
    print("Name: \(name ?? "Nobody"), Age: \(age ?? 0)")
}

1-3. JSON 데이터 쿼리

SwiftyJSON을 사용하여 JSON 데이터의 특정 부분을 쉽게 쿼리할 수 있다.

import SwiftyJSON

let json = JSON(["fruits": ["apple", "banana", "orange"]])

// JSON 데이터에서 배열 추출
let fruitsArray = json["fruits"].arrayValue

for fruit in fruitsArray {
    print(fruit.stringValue)
}

1-4. 사용하지 않았을 때 VS 사용했을 때

SwiftyJSON를 사용하지 않은 경우

일반적으로 do-catch, try를 이용한다.

import Foundation

let jsonString = "{\"name\": \"Junyoung\", \"age\": 26}"

if let jsonData = jsonString.data(using: .utf8) {
    do {
        if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
            if let name = json["name"] as? String, let age = json["age"] as? Int {
                print("Name: \(name), Age: \(age)")
            }
        }
    } catch {
        print("JSON parsing error: \(error)")
    }
}

SwiftyJSON를 사용한 경우

import SwiftyJSON

let jsonString = "{\"name\": \"Junyoung\", \"age\": 26}"

if let jsonData = jsonString.data(using: .utf8) {
    let json = try? JSON(data: jsonData)
    
    let name = json?["name"].stringValue
    let age = json?["age"].intValue
    
    print("Name: \(name ?? "N/A"), Age: \(age ?? 0)")
}

1-5. OpenWeather API 활용하기

OpenWeather API는 날씨에 관련한 API로 많은 사람들이 사용하고 있는 API 중 하나이다. 이 API의 구조부터 보면 다음과 같다.

SwiftyJSON를 사용하지 않은 경우

struct Weather {
    let cityName: String
    let temperature: Double
    let weatherDescription: String
    
    init(data: [String: Any]) {
        cityName = data["name"] as? String ?? ""
        if let main = data["main"] as? [String: Any], let temp = main["temp"] as? Double {
            temperature = temp
        } else {
            temperature = 0.0
        }
        
        if let weather = data["weather"] as? [[String: Any]], let description = weather[0]["description"] as? String {
            weatherDescription = description
        } else {
            weatherDescription = ""
        }
    }
}

func fetchWeatherData() {
    // OpenWeather API로부터 데이터 가져오기
    
    if let jsonData = jsonString.data(using: .utf8) {
        do {
            if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                let weather = Weather(data: json)
                
                print("City: \(weather.cityName)")
                print("Temperature: \(weather.temperature)°C")
                print("Description: \(weather.weatherDescription)")
            }
        } catch {
            print("JSON parsing error: \(error)")
        }
    }
}

SwiftyJSON를 사용한 경우

import SwiftyJSON

struct Weather {
    let cityName: String
    let temperature: Double
    let weatherDescription: String
    
    init(json: JSON) {
        cityName = json["name"].stringValue
        temperature = json["main"]["temp"].doubleValue
        weatherDescription = json["weather"][0]["description"].stringValue
    }
}

func fetchWeatherData() {
    // OpenWeather API로부터 데이터 가져오기
    
    if let jsonData = jsonString.data(using: .utf8) {
        let json = try? JSON(data: jsonData)
        
        let weather = Weather(json: json)
        
        print("City: \(weather.cityName)")
        print("Temperature: \(weather.temperature)°C")
        print("Description: \(weather.weatherDescription)")
    }
}

1-6. Alamofire와 함께 사용하기

SwiftyJSON은 JSON 데이터를 쉽게 파싱하기 때문에 Alamofire와 같이 사용되기도 한다. 위의 OpenWeatherAPI에서 날씨 데이터를 가져오는 코드를 작성해보면 다음과 같다.

import Alamofire
import SwiftyJSON

struct Weather {
    let cityName: String
    let temperature: Double
    let weatherDescription: String
    
    init(json: JSON) {
        cityName = json["name"].stringValue
        temperature = json["main"]["temp"].doubleValue
        weatherDescription = json["weather"][0]["description"].stringValue
    }
}

func fetchWeatherData(forCity city: String) {
    let apiKey = "API_KEY"
    let apiUrl = "https://api.openweathermap.org/data/2.5/weather?q=\(city)&appid=\(apiKey)"
    
    Alamofire.request(apiUrl).responseJSON { response in
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            let weather = Weather(json: json)
            
            print("City: \(weather.cityName)")
            print("Temperature: \(weather.temperature)°C")
            print("Description: \(weather.weatherDescription)")
            
        case .failure(let error):
            print("Network request failed with error: \(error)")
        }
    }
}

fetchWeatherData(forCity: "New York")
profile
iOS 개발자를 향해 성장 중

0개의 댓글