Skip to content

Instantly share code, notes, and snippets.

@froggomad
Last active June 10, 2021 16:24
Show Gist options
  • Save froggomad/abf79d0703eadae41cd8423bf4424d79 to your computer and use it in GitHub Desktop.
Save froggomad/abf79d0703eadae41cd8423bf4424d79 to your computer and use it in GitHub Desktop.
Swift 5 Async/Await
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
detach { [weak self] in
do {
try await print(self?.getKennyDubroff())
} catch {
print(error) // present error after customizing errors
}
}
}
private func getKennyDubroff() async throws -> String? {
let kenny = Kenny()
return try await kenny.get()
}
}
actor Kenny {
private let url: URL
init(url: URL = URL(string: "https://www.kennydubroff.com")!) {
self.url = url
}
func get() async throws -> String? {
async let data = try URLSession.shared.data(with: url)
return await String(data: try data, encoding: .ascii)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment