천원의 개발

iOS URLSession 정리 본문

iOS&Swift🍎/iOS

iOS URLSession 정리

천 원 2022. 10. 17. 09:06

URLSession ?

  - 앱이 서버와 통신하기 위해 애플이 만들어둔 API입니다.

  - 서버 통신을 위한 라이브러리인 Alamofire, moya 등 의 기반이 되는 API입니다.

  - 서버에서 받아온 데이터를 어떤식으로 동작할지를 설정할 수 있습니다. ex) 타임아웃, 캐시 정책, 백그라운드 데이터 전송 등

 

 

URLSessionConfiguration

  - 서버와 통신시 세부적인 동작과 정책을 설정할 수 있습니다.

 

• Shared Session

 - 싱글턴 패턴 구조로 기본 설정이 되어 있어 단순한 네트워크 요청을 할 때 주로 사용이 되고, 커스터마이징은 할 수 없습니다.

 - 구현이 간단한 장점이 있지만, 백그라운드 전송을 지원하지 않습니다.

let url = URL(string: "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=\(drwNo)")!

// 싱글턴 구조
URLSession.shared.dataTask(with: url)  { data, response, error in
	...
}

 

 Default Session

  - Shared Session과 기본 설정이 유사하게 되어 있습니다. 하지만 커스터마이징이 가능합니다.

  - 네트워크 응답에 대해서는 Delegate 를 통해 세부적인 제어가 가능합니다.

 

let url = URL(string: "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=\(drwNo)")!
let defaultSession = URLSession(configuration: .default)

defaultSession.dataTask(with: url) { data, response, error in
	...
}.resume()

 

 

 Ephemeral Session

  - Shared Session과 기본 설정이 유사하게 되어 있지만 쿠키, 캐시, 인증 정보 등을 디스크에 기록하지 않습니다.

  - private 기능 등을 구현할 때 사용

 

let url = URL(string: "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=\(drwNo)")!
let ephemeralSession = URLSession(configuration: .ephemeral)

ephemeralSession.dataTask(with: url) { data, response, error in
	...
}.resume()

 

 

Background Session

  - 앱이 실행중이지 않을때나 백그라운드 상태에서도 데이터를 다운로드 하거나 업로드 할 수 있습니다.

 

let url = URL(string: "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=\(drwNo)")!

let config = URLSessionConfiguration.background(withIdentifier: "com.yourapp.bundleidentifier")
let backgroundSession = URLSession(configuration: config)

 backgroundSession.dataTask(with: url) { data, response, error in
 	...
 }.resume

 

Task

  - Session 객체가 서버로 요청을 보낸 후, 응답을 받을 때 URL 기반의 내용들을 받는 역할을 합니다

  - 데이터를 전달하는 방식과 구현하려는 목적에 따라 Task 타입이 존재합니다.

 

  • DataTask

  • UploadTask

  • DownloadTask

  • StreamTask

 

 

Request

  - 서버로 요청을 보낼 때 어떻게 데이터를 캐싱할 것인지, 어떤 HTTP 메소드를 사용할 것인지(Get, Post 등), 어떤 내용을 전송할 것인지 등을 설정할 수 있습니다.

 

let url = URL(string: "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=\(drwNo)")!

var request = URLRequest(url: url)
request.setValue("key", forHTTPHeaderField: "테스트") // Header 추가해서

URLSession.shared.dataTask(with: request) { data, response, error in
	...
}.resume()

 

 

Response

 

- 프로토콜 및 URL 스키마와 관계없이 URL 로드 요청에 대한 응답과 관련된 메타데이터 입니다.

- 2가지의 방식으로 response를 받습니다.

 

Completion Handler - completion handler 형태로 응답을 받을 수 있고, 이는 Task가 종료되고 난 후 한 번만 호출이 됩니다.

let url = URL(string: "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=\(drwNo)")!
let defaultSession = URLSession(configuration: .default)

// Completion Handler 방식
defaultSession.dataTask(with: url) { data, response, error in
	...
}.resume()

 

 

    URLSessionDelegate - Task가 실행되는 동안 발생할 수 있는 다양한 상황에 대해서 세부적으로 처리를 하고자 할 때 사용합니다. 

let url = URL(string: "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=\(drwNo)")!

let config = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: config, delegate: self, delegateQueue: nil) //Delegate 채택

let Task = defaultSession.dataTask(with: url)
Task.resume()

extension LottoViewController: URLSessionDataDelegate {
    
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        ...
    }
    
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        ...
    }
    
}

 

 

여기까지 URLSession 정리였습니다.

 

 

 

 

출처: 

https://developer.apple.com/documentation/foundation/urlsession

🌱SeSAC iOS 2기 41회차