-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use async/await with URLSession #1
Comments
WWDC21) Use async/await with URLSessionUse async/await with URLSession *본 글은 WWDC 를 보고, 번역 및 요약 그리고 실행해보는 스터디 프로젝트의 일환입니다. 들어가며
Swift Concurrency(동시성) 장점
네트워킹은 본질적으로 비동기식으로 이루어지고 있습니다. iOS 15, macOS Monterey에서는 Swift 동시성 기능을 활용할 수 있도록 URLSession에 새로운 API 세트를 도입했습니다. 기존 코드(Completion handler를 곁들인)func fetchPhoto(url: URL, completion: @escaping (UIImage?, Error?) -> Void) {
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
completion(nil, error)
}
if let data = data,
let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 {
// main 스레드에서 돌리는 이유?
DispatchQueue.main.async {
completion(UIImage(data: data), nil)
}
} else {
completion(nil, DogsError.invaildServerResponse)
}
}
task.resume()
} 제어흐름
스레딩
async/await을 이용한 코드func fetchPhoto(url: URL) async throws -> UIImage {
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw DogsError.invaildServerResponse
}
guard let image = UIImage(data: data) else {
throw DogsError.unsupportedImage
}
return image
}
Uploadvar request = URLRequest(url: url)
request.httpMethod = "POST"
let (data, response) = try await URLSession.shared.upload(for: request, fromFile: fileURL)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw MyNetworkingError.invaildServerResponse
} |
The text was updated successfully, but these errors were encountered: