How to not freeze the UI, and wait for response?

主宰稳场 提交于 2019-12-04 20:51:38

You are still performing work on the main thread.. async only makes the createData() method to return before the task is completed.. but the task will still be processed at some time in the main thread and during this time your application will become unresponsive.. try using a global queue instead.. to keep your main thread clean..

Dont forget to perform all your UI work on the main thread after getting your response.

Use the asynchronous function instead and call the completion block inside create function's completion.

func createData(request:Crudpb_CreateRequest, with completion: @escaping (String) -> Void) throws { 
try! self.client.create(request) { (response: Crudpb_CreateResponse?, result: CallResult) in 
  DispatchQueue.main.async {
// This is assuming your completion involves UI operations. Otherwise there is no need for this async call.

let stringOutput = String(data: result.resultData!, encoding: String.Encoding.utf8))
    completion(stringOutput)
    }
  }
}

Remove DispatchQueue.main.async block from the createData method

func createData(request:Crudpb_CreateRequest, with completion: @escaping (String) -> Void) throws {
    self.response = try! self.client.create(request)
    completion(self.response.result)
}

Use main queue only where you update the UI from the api response

myobj.createData(request: request, with: { string in
    print(string)//background thread
    DispatchQueue.main.async {
        self.label.text = sting//main thread
    }
})

The UI freeze because you are doing too much work on the main thread. You should find out what function blocks the main thread. The instruments time profiler is an easy way to see which function is spending too much time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!