iOS/iOS Swift Udemy - AngelaYu

Sec13 149) Networking - URL Session

Developer-Michelle 2022. 12. 27. 09:15

<Networking>

Your App -----------> Web Server

                  Request (API 규약에 의해) Query(i.e. city name) 로서 보낸다

                <----------

                  Response

 

How

1. Create a URL

2. Create a URL Session

3. Give URLSession a task.

4. Start the task

 

func performRequest(urlString: String) {

//        1. Create a URL

        if let url = URL(string: urlString) {

//        2. Create a URL Session

            let session = URLSession(configuration: .default)

//        3. Give URLSession a task.

            let task = session.dataTask(with: url, completionHandler:(Data?, URLResponse?, Error?) -> Void)

//        4. Start the task

            task.resume()

        }

    }

 

completionHandler  안에는 함수가 들어간다. ( ) 괄호가 있고 Void라는 반환값을 가지는 것에서 함수라는 것을 알 수 있다.

data를 서버로부터 받아오는 동안 앱은 가만히 있을 수 없기 때문에 그동안 completionHanlder 부분을 수행한다. (completion 되면 그에따라 이 함수가 실행됨)

 

safe data인 경우에만 dataString 으로 print가 됨.

 

let task = ~~ 부분이 실행될 때, task가 trigger되어 handle()을 실행시키는 역할을 한다.

 

이 때 주의 사항: ATS 설정 잊지 말 것 (http로 시작하는 도메인 : not secure 하다고 느낌)

 


JSON Parsing

 

예를 들어서 서버로부터 description 정보를 가지고 오고 싶을 때? 어떻게 가져올 수 있는가?

print(decodedData.weather[0].description)

func parseJSON(weatherData: Data) {

        let decoder = JSONDecoder()

        do {

            let decodedData = try decoder.decode(WeatherData.self, from: weatherData)

            print(decodedData.weather[0].description)

        } catch {

            print(error)

        }

    }

 

위에처럼 불러오기 위해서

 

WeatherData.swift

import Foundation

struct WeatherData: Decodable {

    let name: String

    let main: Main

    let weather: [Weather]

}

 

struct Main: Decodable {

    let temp: Double

}

 

struct Weather: Decodable {

    let description: String

}

 


참고 )

JSON Data to String ?

String(data: data!, encoding: .utf8)

 

https://stackoverflow.com/questions/39616821/swift-3-0-data-to-string