iOS/코드조각

[iOS, Swift] urlSession network 통신

검은참깨두유vm 2022. 8. 15. 17:43
반응형

iOS 15.5, Xcode 13.31, Swift 5, UIKit 환경에서 진행했습니다.

 

// network
func requestMovieAPI() {
    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)

    var components = URLComponents(string: "https://itunes.apple.com/search")

    let term = URLQueryItem(name: "term", value: "marvel")
    let media = URLQueryItem(name: "media", value: "movie")

    components?.queryItems = [term, media]

    guard let url = components?.url else {
        return
    }

    var request = URLRequest(url: url)
    request.httpMethod = "GET"

    let task = session.dataTask(with: request) { data, response, error in
        print( (response as! HTTPURLResponse).statusCode )
        if let hasData = data {
            do {
                self.movieModel = try JSONDecoder().decode(MovieModel.self, from: hasData)
                print(self.movieModel ?? "no data")
            } catch {
                print(error)
            }
        }
    }

    task.resume()
    session.finishTasksAndInvalidate()
}

참고자료 : 인프런 iOS14 실무 가이드

반응형