2

I have completion handler in following function

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()

    }

The dispatch async in above function is giving error

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

The error statement is

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

How to correct this error ?

I am calling this function

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

It is giving error

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

How to correct the function call?

1 Answers1

3

This is the modern (Swift 3 and later) syntax:

DispatchQueue.main.async { completionHandler(appCategories) }
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • I am trying to call this function with parameters completions handler.Is this right way to call that function?...AppCategory.fetchFeatureApp { (appcategories) in self.appcategories = appcategories self.collectionView?.reloadData() } –  Dec 02 '17 at 12:24