How to make async / await in Swift?

后端 未结 5 2016
别跟我提以往
别跟我提以往 2020-12-28 14:53

I would like to simulate async and await request from Javascript to Swift 4. I searched a lot on how to do it, and I thought I found the answer with DispatchQueue

5条回答
  •  旧时难觅i
    2020-12-28 15:43

    You can use this framework for Swift coroutines - https://github.com/belozierov/SwiftCoroutine

    Unlike DispatchSemaphore, when you call await it doesn’t block the thread but only suspends coroutine, so you can use it in the main thread as well.

    func awaitAPICall(_ url: URL) throws -> String? {
        let future = URLSession.shared.dataTaskFuture(for: url)
        let data = try future.await().data
        return String(data: data, encoding: .utf8)
    }
    
    func load(url: URL) {
        DispatchQueue.main.startCoroutine {
            let result1 = try self.awaitAPICall(url)
            let result2 = try self.awaitAPICall2(result1)
            let result3 = try self.awaitAPICall3(result2)
            print(result3)
        }
    }
    

提交回复
热议问题