-
URLSession: 서버와 소통하는 주체, Json Decodecode 2024. 2. 20. 22:29
response status code가 200번대이어야함.
URLSession.shared.dataTaskPublisher(for: request) .tryMap { result -> Data in guard let response = result.response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else { let response = result.response as? HTTPURLResponse let statusCode = response?.statusCode ?? -1 throw NetworkError.responseError(statusCode: statusCode) } return result.data }
URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { print("Error: \(error.localizedDescription)") return } if let data = data { do { //Data를 decode, 형식이 MyData이다. let decodedData = try JSONDecoder().decode(MyData.self, from: data) DispatchQueue.main.async { self.data = decodedData } } catch { print("Error decoding data: \(error.localizedDescription)") } } }
Data를 decode, 형식이 MyData이다.
'code' 카테고리의 다른 글
[SwiftUI] Firestore로 채팅 기능 구현하기 (0) 2023.10.26 [Swift] Realm 스레딩 이용시 주의사항 - Realm은 하나의 스레드에서 작업이 이루어져야 한다 (0) 2023.03.17 지정생성자vs편의생성자, 클래스와 인스턴스의 메모리 구조 차이 (0) 2023.03.15 리스트에 자료 추가하기 (0) 2022.10.20 cvs 파일 python에서 쓰기 (0) 2022.10.20