DispatchQueue不更新 迅速的数据

问题描述 投票:1回答:1

我需要做的雨燕中的搜索操作和使用我的的UISearchBar它。

在textDidChange事件,我需要调用Web API,解析响应,然后更新数组,然后开始更新阵列上的搜索。

但不知道我的代码不能正常工作。

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    let group = DispatchGroup()
    group.enter()
    // Perform some asynchronous operation
    let queue1 = DispatchQueue(label: "abc")
    queue1.async {
        self.callWebAPI() // This function calls the web api and parses it’s response
        group.leave()
    }

    DispatchQueue.global(qos: .utility).async {
        DispatchQueue.main.async {
            self.filteredCountry = self.arrCountry.filter({$0.name.prefix(searchText.count) == searchText})
            self.searching = true
            self.tableView.reloadData()
        }
    }
}

func callWebAPI() {
    let urlString = URL(string: "https://restcountries.eu/rest/v2/all")
    if let url = urlString {
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error!)
            } else {
                if let usableData = data {
                    do{
                        //here dataResponse received from a network request
                        let jsonResponse = try JSONSerialization.jsonObject(with:
                            data!, options: [])
                        print(jsonResponse) //Response result

                        guard let jsonArray = jsonResponse as? [[String: Any]] else {
                            return
                        }


                        print(jsonArray)

                        print("done")

                    } catch let parsingError {
                        print("Error", parsingError)
                    }

                }
            }
        }
        task.resume()
    }

}

请指导我上面的代码不知道在哪里,我错了

swift asynchronous search nsoperation
1个回答
0
投票

问题是,callWebAPI是异步的(它返回请求完成之前),所以你立即调用leave。你可以给这个方法完成处理程序,并在调用leave。而你也将调用在notify块的UI更新您的团队,而不只是派遣了。

简单,只要退休DispatchGroup完全,只是更新您提供给callWebAPI完成处理您的UI。

例如,给callWebAPI完成处理程序:

func callWebAPI(completionHandler: @escaping ([[String: Any]]?, Error?) -> Void) {
    let urlString = URL(string: "https://restcountries.eu/rest/v2/all")
    if let url = urlString {
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data, error == nil else {
                completionHandler(nil, error)
                return
            }

            do {
                let jsonResponse = try JSONSerialization.jsonObject(with:
                    data)

                completionHandler(jsonResponse as? [[String: Any]], nil)
            } catch let parsingError {
                completionHandler(nil, parsingError)
            }
        }
        task.resume()
    }
}

然后,你可以消除调度组,全局队列(因为它已经是一个异步方法,你不必从背景队列调用此)等,它简化为:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    callWebAPI { jsonResponse, error in
        guard let jsonResponse = jsonResponse, error == nil else {
            print("Error:", error ?? "Response was not correct format")
            return
        }

        print(jsonResponse)

        // Note, you don’t appear to be using `jsonResponse` at all,
        // so I presume you’d update the relevant model objects.

        DispatchQueue.main.async {
            self.filteredCountry = self.arrCountry.filter({$0.name.prefix(searchText.count) == searchText})
            self.searching = true
            self.tableView.reloadData()
        }
    }
}

顺便说一句,现在我们使用JSONDecoder解析JSON填充模型直接对象,但已经超出了问题的范围。

© www.soinside.com 2019 - 2024. All rights reserved.