swift - 完成处理程序dispatch_async给出错误?

标签 swift grand-central-dispatch dispatch-async completionhandler

我在以下函数中有完成处理程序

static func fetchFeatureApp(completionHandler:@escaping ([AppCategory1])->()){
        let urlString="http://ebmacs.net/ubereats/Api/all_product?id=1"
        let url = URL(string: urlString)!

     URLSession.shared.dataTask(with: URLRequest(url: url)){ (data, responce, error) in
        if error != nil
            {
                print(error)
                return
            }
        do {
            if let jsonResult = try JSONSerialization.jsonObject(with:data!) as? [String:Any] {
                if let products = jsonResult["products"] as? [[String:String]] {
                    var appCategories = [AppCategory1]()
                    for product in products {
                        let category = AppCategory1(id: product["product_id"] ?? "",
                                                   name: product["product_name"] ?? "",
                                                   description: product["product_description"] ?? "",
                                                   url: product["image_url"] ?? "",
                                                   price: product["product_price"] ?? "")
                        appCategories.append(category)
                    }
                     print("Abc=")
                    print(appCategories)
                    dispatch_async(dispatch_get_main_queue(), {
                        completionHandler(appCategories)
                    })

                }
            }
        } catch {
            print(error)
        }
        }.resume()

    }

上述函数中的调度异步给出错误

  dispatch_async(dispatch_get_main_queue(), {
                    completionHandler(appCategories)
                })

错误语句为

'dispatch_async' has been replaced by instance method 'DispatchQueue.async(execute:)' 'dispatch_get_main_queue()' has been replaced by property 'DispatchQueue.main'

如何纠正这个错误?

我正在调用此函数

 AppCategory.fetchFeatureApp { (appcategories) in
            self.appcategories = appcategories
            self.collectionView?.reloadData()
        }

出现错误

Value of type 'FeaturedViewController' has no member 'appcategories'

如何修正函数调用?

最佳答案

这是现代(Swift 3 及更高版本)语法:

DispatchQueue.main.async { completionHandler(appCategories) }

关于swift - 完成处理程序dispatch_async给出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47605566/

相关文章:

ios - 如果操作未完成,iPhone 应用程序会因dispatch_async 崩溃

swift3 - 长循环 block 应用

IOS/objective-C : returning to main thread

ios - 在 UITableView 中自定义每个单元格的分隔符

ios - 为什么查询(DBAccess)第一次在 Id 属性中返回 nil?

ios - 我如何在 VIMVideoPlayer URL restricted 中播放 vimeo 视频

multithreading - dispatch_queue 和核心数据

objective-c - ARKit – 空间音频几乎不会随距离改变音量

ios - 异步操作并发理解

ios - 如何在iOS上使用Dispatch Queue问题?