How to make async / await in Swift?

后端 未结 5 2027
别跟我提以往
别跟我提以往 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条回答
  •  鱼传尺愫
    2020-12-28 15:57

    You can use semaphores to simulate async/await.

    func makeAPICall() -> Result  {
                let path = "https://jsonplaceholder.typicode.com/todos/1"
                guard let url = URL(string: path) else {
                    return .failure(.url)
                }
                var result: Result !
                
                let semaphore = DispatchSemaphore(value: 0)
                URLSession.shared.dataTask(with: url) { (data, _, _) in
                    if let data = data {
                        result = .success(String(data: data, encoding: .utf8))
                    } else {
                        result = .failure(.server)
                    }
                    semaphore.signal()
                }.resume()
                _ = semaphore.wait(wallTimeout: .distantFuture)
                return result
     }
    

    And here is example how it works with consecutive API calls:

    func load() {
            DispatchQueue.global(qos: .utility).async {
               let result = self.makeAPICall()
                    .flatMap { self.anotherAPICall($0) }
                    .flatMap { self.andAnotherAPICall($0) }
                
                DispatchQueue.main.async {
                    switch result {
                    case let .success(data):
                        print(data)
                    case let .failure(error):
                        print(error)
                    }
                }
            }
        }
    

    Here is the article describing it in details.

    And you can also use promises with PromiseKit and similar libraries

提交回复
热议问题