Alamofire http json request block ui

前端 未结 2 824
清歌不尽
清歌不尽 2021-01-26 09:50

I\'ve been creating a function which retrieve objects from a JSON script. I\'ve chosen for this to use alamofire for async request and swiftyJSON for easy parsing. However i see

2条回答
  •  情书的邮戳
    2021-01-26 10:33

    Swift5 An update to Stefan Salatic's answer, if you are parsing a large amount of json data from the Alamofire response it is better you use a global dispatch Queue and if for any reason you need to update the UI in the main thread switch to DispatchQueue.main.async.

    So a sample code will look like this.

    AF.request(UrlGetLayers, method: .post, parameters: parameters, headers: headers)
                .responseJSON { response in
                 DispatchQueue.global(qos: .background).async {
                    
                    //parse your json response here
                    
                    //oops... we need to update the main thread again after parsing json
                    DispatchQueue.main.async {
                        
                    }
                    
                 }
    
            }
            
    

提交回复
热议问题