简体   繁体   中英

Populate collectionView from JSON image url swift

I want to Load image using JSON parsing in collectionView. I'm getting array of image URLs, but images are not shown on UIImageView . I have used this code after getting JSON array and displaying it in UICollectionView 's UIImageView .

    if let url = NSURL(string: self.Products[indexPath.row].image) {
        if let data = NSData(contentsOfURL: url){
            cell.product_image.contentMode = UIViewContentMode.ScaleAspectFit
            cell.product_image.image = UIImage(data: data)
        }
    }

But I am not able to load image, but text is displayed. I have used this code in cellForItemAtIndexPath method.. Can anyone suggest me what am I doing wrong?

func jsonParsingFromURL(){
        // 1
        let reposURL = NSURL(string: "http://api.room2shop.com/api/product/GetProducts?categoryId=24&filter=2&pageNumber=1")
        // 2
        if let JSONData = NSData(contentsOfURL: reposURL!) {
            // 3
            do
            {
                if let json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: .AllowFragments) as? NSDictionary {
                    // 4
                    if let reposArray = json["ProductList"] as? [NSDictionary] {
                        // 5
                        for item in reposArray {
                            Products.append(ProductList(json: item))
                        }
                    }
                }
            }
            catch {
                print("Error with Json: \(error)")

            }
        }
    }

This is my JSON parsing code

to reflect changes, you need to use

self.collectionView?.reloadData()

EDIT

1- please replace this block with this, and tell me if you get the urls normally, for me I get the urls normally

                for item in reposArray
                {
                    //ProductList(json: item)
                    //Products.append(ProductList(json: item))
                    //print(item)
                    print("__________")
                    print(item["Image"]!)

                }

2- i was getting

Transport Security has Blocked a cleartext HTTP

solution was here. Transport security has blocked a cleartext HTTP

use this

// taking the URL , then request image data, then assigne UIImage(data: responseData)
            let imgURL: NSURL = NSURL(string: "www.example.com/image.jpg")!
            let request: NSURLRequest = NSURLRequest(URL: imgURL)
            let session = NSURLSession.sharedSession()
            let task = session.dataTaskWithRequest(request) {
                (data,response,error) -> Void in
                if ( error == nil && data != nil ) {
                    func display_image() {
                    // imageView.post.image = your UIImage  
                    self.imageViewPost.image = UIImage(data: data!)
                    }

                    dispatch_async(dispatch_get_main_queue(), display_image)
                }
            }
            task.resume()
            // end of loading img

The image is a URL which is not saved locally inside the image.xassets , so you need to parse the URL using the extension given below.

// add the extension

extension UIImageView {

    func loadImage(urlString: String)  {
        let url =  URL(string: urlString)!
       URLSession.shared.dataTask(with: url, completionHandler: { (data, respones, error) in

            if error != nil {
                print(error ?? "")
                return
            }


            DispatchQueue.main.async {
                self.image = UIImage(data: data!)
            }


        }).resume()

    }
}

// call this statement in your vc (where you polpulate)

yourImageView.loadImage(urlString:yourUrl)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM