URLSession이란 ?
앱과 서버간의 데이터를 주고받기 위해서는 HTTP 프로토콜을 이용해서 데이터를 주고 받아야합니다.
URLSession이란 앱에서 서버와 통신하기 위해 애플이 제공하는 API로 HTTP를 포함한 몇가지 프로토콜을 지원하고, 인증 / 쿠키 관리 / 캐시 관리 등을 지원합니다.
즉, iOS 앱에서 네트워킹을 하기 위해 필요한 API입니다.
URLSession 사용 순서
- Configuration 결정
- Session 생성
- Request에 사용할 url 설정
- Task 결정 및 작성
URLSessionConfiguration
URLSession을 생성하기 위해 필요한 요소입니다.
Configuration을 생성할 때는 URLSession 정책에 따라 Default, Ephemeral, Background 세 가지의 형태로 생성됩니다.
- Default: 기본 통신으로 디스크 기반 캐싱을 지원합니다.
- Ephemeral: 쿠키나 캐시를 저장하지 않는 정책을 가져갈 때 사용합니다.
- Background: 앱이 백그라운드에 있는 상황에서 컨텐츠 다운로드, 업로드를 할 때 사용합니다.
URLSessionDelegate
네트워크 중간 과정을 확인할 수 있으며 필요에 따라 사용됩니다.
URLSessionTask
작업에 따라 세 가지로 나뉩니다.
1. DataTask
Data를 받는 작업으로 Response 데이터를 메모리 상에서 처리하게 됩니다.
Background Session에 대한 지원이 되지 않습니다.
URL 요청을 실시하고 완료 시 handler를 호출하는 방식입니다.
Task가 실행된 후 handler가 실행되기 때문에 탈출 closure 형태로 받아와야 합니다.
2. UploadTask
파일을 업로드할 때 사용합니다.
3. DownloadTask
파일을 다운로드 받아서 디스크에 쓸 때 사용합니다.
URLSession 실습
Configuration 결정 및 Session 생성
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
Request에 사용할 url 설정
let url = URL(string: "https://url.com")
let request: URLRequest = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Task 생성
1. URLSessionDataTask
// url: 검색할 URL
func dataTask(with url: URL,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
// request: URL, 캐시 정책, 요청 유형, body data, body stream 등을 제공하는 URL 요청 객체
func dataTask(with request: URLRequest,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
2. URLSessionUploadTask
// request: URL 요청 객체로 body data 및 body stream은 무시
// fileURL: 업로드 할 파일의 URL
func uploadTask(with request: URLRequest,
fromFile fileURL: URL,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionUploadTask
// bodyData: 요청을 위한 body data
func uploadTask(with request: URLRequest,
from bodyData: Data?,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionUploadTask
completionHandler
- data : 서버로부터 전달받은 data
- response : HTTP 헤더 및 status code 같은 response metadata를 제공하는 객체
- error : 요청이 실패한 이유를 의미하는 error 객체로 요청이 성공적이면 nil
3. URLSessionDownTask
func downloadTask(with url: URL,
completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> URLSessionDownloadTask
func downloadTask(with request: URLRequest,
completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> URLSessionDownloadTask
completionHandler
- location (URL?) : 서버의 response가 저장되는 임시파일의 위치로 completion handler가 리턴되기 전까지 읽기 위해서 열어야합니다. 그렇지 않으면 파일이 삭제되고 손상됩니다.
- error : 요청이 실패한 이유를 의미하는 error 객체로 요청이 성공적이면 nil입니다.
예제 코드
// Configuration 및 Session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// url
guard let url = URL(string: "https://url.com") else { return }
// Request
let request = URLRequest(url: url)
// Task
let dataTask = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
guard let err == nil else {
print("error")
return
}
guard let data = data, let response = response as? HTTPURLResponse, response.statusCode == 200 else {
return
}
// data 처리
}.resume()
참고
https://gyuios.tistory.com/106?category=959916
https://greatpapa.tistory.com/66
'iOS > iOS' 카테고리의 다른 글
[iOS] UIView.frame과 UIView.bounds (0) | 2023.09.04 |
---|---|
[iOS] strong / weak / unowned / 순환 참조 (0) | 2022.09.08 |
[iOS] ARC (Automatic Reference Counting) (0) | 2022.09.08 |