220v
젝무의 개발새발
220v
전체 방문자
오늘
어제
  • 분류 전체보기 (255)
    • AI (35)
      • ML, DL 학습 (30)
      • 논문 리뷰 (4)
      • 실습 및 프로젝트 (1)
    • Algorithm (145)
      • LeetCode (13)
      • 프로그래머스 (35)
      • 백준 (96)
      • 알고리즘, 문법 정리 (1)
    • Mobile, Application (17)
      • Flutter (10)
      • iOS, MacOS (7)
    • BackEnd (7)
      • Flask (1)
      • Node.js (5)
      • Spring, JSP..etc (1)
    • Web - FrontEnd (18)
      • JavaScript, JQuery, HTML, C.. (12)
      • React (6)
    • DataBase (1)
      • MySQL (1)
      • Firebase Firestore (0)
      • Supabase (0)
    • Git (1)
    • 기타 툴 및 오류 해결 (3)
    • 강의 (5)
      • Database (3)
      • 암호학 (2)
      • 알고리즘 (0)
    • 후기와 회고 (2)
    • 블로그 꾸미기 (1)
    • 일상과 이것저것 (20)
      • 맛집 (12)
      • 세상사는일 (4)
      • 도서리뷰 (1)
      • 이런저런 생각들 (잡글) (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • disjoint set
  • union-find
  • 백준
  • simulation
  • implementation
  • Dynamic Programming
  • 다익스트라
  • Priority Queue
  • top-down
  • 티스토리챌린지
  • Backtracking
  • dp
  • Mathematics
  • Lis
  • Greedy
  • Prefix Sum
  • brute-Force
  • bitmasking
  • BFS
  • dfs
  • binary search
  • REACT
  • Minimum Spanning Tree
  • 오블완
  • 구현
  • 위상 정렬
  • 프로그래머스
  • IMPLEMENT
  • topological sort
  • two pointer

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
220v

젝무의 개발새발

Mobile, Application/iOS, MacOS

[Swift] URLSession 간단 요약

2023. 9. 24. 22:05

URLSession이란?

  • An object that coordinates a group of related, network data transfer tasks.
  • API 통신을 하기 위한 클래스.
  • 데이터를 업로드 / 다운로드하는 데에 사용
  • 앱이 실행중이지 않을 때, 백그라운드에서도 통신이 가능.

하나의 URLSession에서 여러 개의 URLSessionTask 인스턴스를 만들 수 있으며, URLSessionTask 각각은 데이터를 fetch하거나, 업로드하거나, 파일을 다운로드하는 역할을 할 수 있다.

 

URLSession의 Request와 Response

  • URLSession은 다른 HTTP 통신과 마찬가지로 Request와 Response를 기본 구조로 가진다.

  • Request

    • URL 객체를 통해 직접 통신하는 형태
    • URLRequest 객체를 만들어서 옵션을 설정하여 통신하는 형태
  • Response

    • 설정된 Task의 Completion Handler 형태로 response를 받는 형태
    • (+) async/await 으로도 비동기 처리 가능 !
    • URLSessionDelgate를 통해 지정된 메소드를 호출하여 response 를 받는 형태

    간단한 response → Completion Handler

    백그라운드에서도 지원하거나, 인증, 캐싱을 default 옵션으로 사용하지 않을 때 → Delegate 패턴

 

URLSession’s Life Cycle

  1. Session configuration을 결정, Session을 생성 (shared 제외)
  2. 통신할 URL과 Request 객체를 설정 (Request 작성)
  3. 사용할 Task를 결정, 그에 맞는 Completion Handler나 Delegate 메소드 작성
  4. 해당 Task를 실행 (.resume())
  5. Task 완료 후 Completion Handler가 실행.

 

URLSession Configuration

.default Session

.default Session은 추가로 사용자 지정하지 않은 한 shared Session과 비슷하게 동작

shared와는 다르게 delegate를 할당, 데이터 fetching 가능.

→ 기본적인 방법.

.ephemeral Session

.ephemeral Session은 .default Session과 비슷하지만 cache, cookies, credential를 디스크에 쓰지 않음.

→ 쿠키, 캐시, 인증(credential)을 저장할 일이 없을 때 사용 (ex. 크롬 시크릿 창 등)

.background Session

.background Session은 앱이 실행되지 않는 동안 Background에서 콘텐츠 업로드, 다운로드를 수행.

→ 백그라운드 실행이 필요할 때 사용

// configuration이 default인 URLSession 객체 생성
let defaultSession = URLSession(configuration: .default)

// URLSessionConfiguration 객체를 생성 후, URLSession 객체 생성 시 사용
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)

 

URLSession Task

Data Task

Get 통신으로 데이터를 fetching할 때 사용.

Upload Task

POST, PUT 통신으로 데이터를 upload할 때 사용.

background upload를 지원.

Download Task

특정 URL로부터 파일 등을 download할 때 사용. (ex. 음악 파일, 사진 파일 등)

background download를 지원.

Stream Task

양방향의 TCP/IP 통신을 구현할 때 사용.


예시: dataTask(with: completionHandler:)

func dataTask(
    with request: URLRequest,
    completionHandler: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void
) -> URLSessionDataTask
  • request parameter에는 URLRequest 객체를 생성하여 넣어주기.

URLRequest | Apple Developer Documentation

  • Completion Handler 넣어주기. Completion Handler에는 data, response, error parameter가 존재해야 함. (각각 NSData, NSResponse, NSError)
  • *Completion Handler는 nil일 수 있으며, nil 값일 경우, dataTask(with:) 과 동일.
  • *Completion Handler가 존재할 경우, data 전달과 response를 받기 위한 Delegate 함수들은 실행되지 않음.
func getAnimalData(completion: @escaping (String) -> ()) {
	guard let url = URL(string: "<https://Jeckmutest/app/urlsession/dataTask>") else {
	    return
	}
	let request = URLRequest(url: url)
	
	let task = URLSession.shared.dataTask(with: request) { data, response, error in
	    if let error = error {
	        print(error.localizedDescription)
	        return
	    }
	
	    guard let httpResponse = response as? HTTPURLResponse,
	          (200..<300).contains(httpResponse.statusCode) else {
	              print("error")
	              return
	          }
	
	    if let data = data {
	        do {
	            let receivedData = try JSONDecoder().decode(~~~, from: data)
	            completion("성공!")
	        } catch {
	            print(error.localizedDescription)
	        }
	    }
	}
}

task.resume()

Reference

URLSession | Apple Developer Documentation

[Swift] URLSession(1) - 개념 모아보기(URLSession, URLSessionConfiguration, URLSessionTask)

 

    'Mobile, Application/iOS, MacOS' 카테고리의 다른 글
    • [Xcode 15] Xcode 15에서 추가한 시뮬레이터가 보이지 않는 현상
    • [iOS, Swift] NotificationCenter 간단 요약
    • [Swift(iOS, WatchOS), CreateML, CoreML] iOS & WatchOS 앱에 ML 적용해보기 (1) - 모델 생성 및 학습하기 (Activity Classification)
    • [Xcode / Cocoapods] M1 Mac 환경에서 pod init 에러 - (RuntimeError - [Xcodeproj] Unknown object version.)
    220v
    220v
    DGU CSE 20 / Apple Developer Academy @ POSTECH 2nd Jr.Learner.

    티스토리툴바