728x90
사용 함수
- URLSessionConfiguration
- .default: 기본 작업
- .ephemeral: 보안 작업
- .background: 다운로드 작업
- URLSession
- URLSessionDataTask
- URLSessionTask
- dataTask
- uploadTask
- downloadTask
// 예시
import Foundation
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
let url = URL(string: /*"https://..."*/)!
let task = session.dataTask(with: url) { data, response, error in
quard let httpResponse = response as? HTTPURLResponse,
(200..<300).contains(httpResponse.statusCode) else {
return
}
guard let data = data else { return }
let result = String(data: data, encoding: .utf8)
}
task.resume()
- Codable: JSON 인/디코더
// 예시
do {
let decoder = JSONDecoder()
let data = try decoder.decode(/*Codable Structure*/, from: data)
} catch let error as NSError {
print("\(error)")
}
// Network Service Class
import Foundation
import Combine
///// Defines the Network service errors.
enum NetworkError: Error {
case invalidRequest
case invalidResponse
case responseError(statusCode: Int)
case jsonDecodingError(error: Error)
}
final class NetworkService {
let session: URLSession
init(configuration: URLSessionConfiguration) {
session = URLSession(configuration: configuration)
}
func load<T>(_ resource: Resource<T>) -> AnyPublisher<T, Error> {
guard let request = resource.urlRequest else {
return .fail(NetworkError.invalidRequest)
}
return session
.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
}
.decode(type: T.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
}
728x90
'iOS' 카테고리의 다른 글
[단축어] 아이폰으로 갤럭시처럼 전화/문자 보내기 (0) | 2022.08.15 |
---|---|
[iOS] SwiftUI로 NavigationView, GridView, SafariView, NavigationLink 구현하기(Framework) (0) | 2022.08.09 |
[iOS] Combine (0) | 2022.07.23 |
[iOS] 네비게이션(Navigation)과 모달(Modality) (0) | 2022.07.22 |
[iOS] 리스트 및 그리드 뷰 구성하기 (0) | 2022.07.22 |