How I can return value from async block in swift

后端 未结 3 1587
无人及你
无人及你 2020-12-02 02:49

Please have a look into the code below:

backgroundthread.async {
    return self.mycallback() //return string, int etc
}

I want to return a

3条回答
  •  鱼传尺愫
    2020-12-02 03:18

    What you are describing with return self.mycallback() is something like in

    TypeScript:

    String text = await someTask();
    

    or in C#:

    String text = someTask().result;
    

    and from an async function:

    String text = await someTask();
    

    However this concept does not exist in swift (and i think Java too).

    The only other method I can think of other than using a completion handler, is passing the results to another function (NOTE: If you intend on working on the main thread/UI Thread you will get an exception - you will need to wrap your call in DispatchQueue.main.async {/*Do stuff...*/}) like so

        func startAsync {
            let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
            let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
                guard let data = data else { return }
                guard let jsonString = String(data: data, encoding: .utf8) else { return }
                DispatchQueue.main.async {
                    self.setResults(text: jsonString);
                }
            }
            task.resume()
        }
    
        func setResults(text: String?){
            textView.text = text;
        }
    

    full project: https://github.com/AppLogics/SwiftAsyncTaskWithoutCompletionHandler

提交回复
热议问题