Skip to content

Instantly share code, notes, and snippets.

@froggomad
Last active June 9, 2021 16:36
Show Gist options
  • Save froggomad/307ab059009ee18f8f726de266ce3a0a to your computer and use it in GitHub Desktop.
Save froggomad/307ab059009ee18f8f726de266ce3a0a to your computer and use it in GitHub Desktop.
Swift 5 URLSessionDataTask async/await
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
detach { [weak self] in
await print(self?.getGoogle())
}
}
private func getGoogle() async -> String? {
let google = Google(url: .init(string: "https://www.google.com")!)
return try? await google.get()
}
}
actor Google {
var dataString: String?
private let url: URL
private lazy var request = URLRequest(url: url)
init(url: URL) {
self.url = url
}
private func oldCompletionMethod(completion: @escaping () -> Void) {
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print(error)
completion()
}
if let data = data {
self.dataString = String(data: data, encoding: .ascii)
completion()
}
}.resume()
}
private func asyncTask() async {
await withUnsafeContinuation { task in
oldCompletionMethod {
task.resume()
}
}
}
func get() async throws -> String? {
await asyncTask()
return dataString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment