Last active
June 10, 2021 16:24
-
-
Save froggomad/abf79d0703eadae41cd8423bf4424d79 to your computer and use it in GitHub Desktop.
Swift 5 Async/Await
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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