Swift 5.5 async await
ベータ版であるXcode 13をインストールして、Swift 5.5 async await
を勉強して、http GET
を実装してみたのですが、これが最適解ですかね?
import Foundation
class API {
func httpGet(for urlString: String) async throws -> Data? {
guard let url = URL(string: urlString) else {
return nil
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
let (data, _) = try await URLSession.shared.data(for: request)
return data
}
}
class Sample {
var data : String?
func getData() {
async {
let api = API()
guard let data = try await api.httpGet(for: "https://api.isevenapi.xyz/api/iseven/6/") else { return }
if let dataString = String(data: data, encoding: .utf8) {
print(dataString)
self.data = dataString
}
}
}
}
var sample = Sample()
sample.getData()