728x90
이번 장에서는 Combine의 실제 사용 사례를 중심으로 알아보고자 한다.
사실 Combine에서 자주 쓰이는 부분은 URLSession일 것 같다.
URLSession With Combine
// 애플 공식 문서 예시 코드 살짝 수정
struct User: Codable {
let name: String
let userID: String
}
let url = URL(string: "https://example.com/endpoint")!
cancellable = urlSession
.dataTaskPublisher(for: url)
.tryMap() { element -> Data in
guard let httpResponse = element.response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw URLError(.badServerResponse)
}
return element.data
}
.decode(type: User.self, decoder: JSONDecoder())
.sink(receiveCompletion: { print ("Received completion: \($0).") },
receiveValue: { user in print ("Received user: \(user).")})
728x90
'Swift > Apple Framework' 카테고리의 다른 글
[iOS / SwiftUI] Paging 무한 스크롤 (0) | 2023.05.23 |
---|---|
[iOS / SwiftUI] Combine - AnyCancellable (0) | 2023.05.08 |
[iOS / SwiftUI] Combine - CurrentValueSubject, PassthroughSubject (0) | 2023.05.02 |
[SwiftUI] StateObject와 ObservedObject 차이점 (0) | 2023.04.22 |
[iOS / Swift] sort() 는 어떤 알고리즘을 쓸까? (0) | 2023.04.22 |