如何加载uiCollection View Cell表单API

时间:2017-12-05 11:09:08

标签: ios swift api web-services uicollectionview

我已经以编程方式创建了uiCollection View。 我想用来自Web服务的Model类中来自url的数据来填充uiCollection View

struct AppCategory1 {
    let id, name, description, url, price : String
}

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)
                    DispatchQueue.main.async { completionHandler(appCategories) }


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

}

直到现在uicollection视图正在从Model.swift中的函数sampleAppCategories()中硬编码的数据填充文件函数从ViewController.swift文件中调用

 appcategories=AppCategory.sampleAppCategories()

我从ViewController.swift文件中的FeaturedViewController类的viewDidLoad函数调用此函数fetchFeatureApp(completionHandler:@escaping([AppCategory1]) - >())

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

它没有填充uiCollection View.How我可以从url填充Collection View吗?

问题是我使用AppCategory类

对uiCollectionviewController进行了硬编码
class AppCategory: NSObject {
        var name:NSString?
        var apps:[App]?
    }
    class App:NSObject  {
        var product_id:NSNumber?
        var product_name:String?
        var product_description:String?
        var image_url:String?
        var product_price:NSNumber?
        var name:String?
    }

并使用AppCategory1结构从url

获取数据
struct AppCategory1 {
            let id, name, description, url, price : String
        }  //using for getting data url

我正在尝试采用一个结构或类来使集合视图中的url数据可以出现

您可以从此链接下载项目。https://drive.google.com/file/d/1eBcbOLwtEdrCpZ3tDF41_WFsqPlgGo2r/view?usp=sharing

0 个答案:

没有答案