从Api响应填充tableviewcell上的imageview

时间:2017-10-07 18:48:39

标签: uitableview imageview

我是ios的新手并且第一次实施swift 3.我有一个以下类型的json:

[ homeCatArray =     (
                {
            "child_id" = 25;
            image = "HTTP://i.vinove.com/dnn/backend/uploads/banner_saldi_en.png";
            name = "WINTER SALE";
            "parent_id" = 1;
        },
                {
            "child_id" = 4;
            image = "HTTP://i.vinove.com/dnn/backend/uploads/BM_ONDEMAND_EN_NOLOC.jpg";
            name = "FRESH FASHION";
            "parent_id" = 2;
        },
                {
            "child_id" = 11;
            image = "HTTP://i.vinove.com/dnn/backend/uploads/1458204097e-commerce-banner.png";
            name = "";
            "parent_id" = 2;
        },
                {
            "child_id" = 3;
            image = "HTTP://i.vinove.com/dnn/backend/uploads/1458204597banner-4.jpg";
            name = "";
            "parent_id" = 2;
        }
    );
}, "message": Successfull]

我使用以下代码从服务器获取它。

 func webHelper(_ jsonRequest:[String:Any] , url: String ,completionHandler: @escaping CompletionHandler) {

        var request = URLRequest(url:URL(string:url)! )
        request.httpMethod = "POST"
        var dataString = NSString()

        let a = "json_data="

        let data = try! JSONSerialization.data(withJSONObject: jsonRequest, options: [])

        let b = String(data: data, encoding: String.Encoding.utf8)

        let first = a  + b!
        dataString = first as NSString
        dataString = dataString.replacingOccurrences(of: ">",with:"%3E") as NSString

        dataString = dataString.replacingOccurrences(of: "<", with:"%3C") as NSString
        dataString = dataString.replacingOccurrences(of: "&" ,with:"%26") as NSString
        dataString = dataString.replacingOccurrences(of: "'", with:"%E2%80%98") as NSString
        dataString = dataString.replacingOccurrences(of: "£" ,with:"%C2%A3") as NSString
        dataString = dataString.replacingOccurrences(of: "€" ,with:"%u20AC") as NSString
        dataString = dataString.replacingOccurrences(of: "¥" ,with:"%C2%A5") as NSString
        dataString = dataString.replacingOccurrences(of: "₹" ,with:"%u20B9") as NSString
        dataString = dataString.replacingOccurrences(of: "\n", with:"") as NSString
        dataString = dataString.replacingOccurrences(of: "\r" ,with:"") as NSString

        let requestData = dataString.data(using: String.Encoding.utf8.rawValue)
        request.httpBody = requestData
        request.addValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept-Encoding")
        request.addValue("en-US", forHTTPHeaderField: "Accept-Language")
        request.addValue(String(requestData!.count), forHTTPHeaderField: "Content-Length")
         let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
            if error != nil{
                print(error?.localizedDescription ?? "Error")
                let  dict:[String:AnyObject] = Dictionary()
                completionHandler(dict ,false)

                return
            }

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                if let parseJSON = json {
                    let resultValue = parseJSON["code"] as! Int;

                    if resultValue == 200{
                        completionHandler(parseJSON as! Dictionary ,true)
                    }else{
                        let  dict:[String:AnyObject] = Dictionary()
                        completionHandler(dict ,false)
                    }
                }
            } catch let error as NSError {
                print(error)
                let  dict:[String:AnyObject] = Dictionary()
                completionHandler(dict ,false)
            }
        }
        task.resume()


    }

我已经获得了所需的结果,即关键字“图像”的值如下:

WebServiceHelper.sharedInstance.webHelper(["method":"home"], url: webServicesUrl) {
            (response, success)
            in
            print("##########",[response["data"]!])
            if (response["data"] as? [String:Any]) != nil{
                print("true")
                let data = response["data"] as? [String:Any]
                let homeData = data?["homeCatArray"] as? [[String:Any]]
                print("#$%#@",homeData!)
                for item in homeData! {

                    DispatchQueue.main.async {
                         self.content = [item["image"] as! String]
                        self.tableView.reloadData()

                    }
                }
                 print("1111111Content",self.content)
            }
            else{
                print ("false")
            }

然后尝试在tableview单元格中填充imageview,如下所示:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let homeCell  = tableView.dequeueReusableCell(withIdentifier:"cell") as! HomeTVCustomCells

        // or jpg

        if(content.count > 0){
            let imgURL = URL.init(string:content[indexPath.row])
            let testImage = NSData(contentsOf: imgURL!)
        homeCell.homeTVImageView.image = UIImage.init(data: testImage as! Data)
        }
        else{
            homeCell.homeTVImageView.image = #imageLiteral(resourceName: "bags")
        }

        return homeCell
     }
}

我面临的问题是,该服务实际上返回了四个图像,但即使在每次循环重新编码表视图后,我也只能在tableviewcell imageview上看到一个图像。 我不知道我哪里出错。请给出一些指示。任何帮助或指导都将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

你在以下几行中做错了。

for item in homeData! {

                DispatchQueue.main.async {
                     self.content = [item["image"] as! String]
                    self.tableView.reloadData()

                }
            }

对于每次迭代,您只需将新图像分配给self.content。你的self.content应该是一个数组,以便你可以存储所有的图像。你可以做类似下面的事情。

for item in homeData! {
      self.content.append([item["image"] as! String])
            }
DispatchQueue.main.async {
                    self.tableView.reloadData()
                }