1

I want to display UIImage in collectionView.

Get Images Path from Json data.

The image path is acquired from the variable previously assigned I am trying to display an image, but I can not get it.

API is working.

But I attempted to output it to check the value of the variable var photo = [Stores.photos]? But it was not displayed on the console

Also, if you apply imageURL directly, not from variable, the image will be displayed. How can I assign a value to var photo = [Stores.photos]?

StorePhotoCollectionView

class StorePhotoViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

var store_id = ""

var store : [Store]?
var photo : [Store.photos]?

@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var storePhotoUIView: UIView!


override func viewDidLoad() {
    super.viewDidLoad()

    //Request API
    let url = URL(string: "http://localhost:8000/store/api?store_id=" + store_id)
    let request = URLRequest(url: url!)
    let session = URLSession.shared

    let encoder: JSONEncoder = JSONEncoder()
    encoder.dateEncodingStrategy = .iso8601
    encoder.outputFormatting = .prettyPrinted

    session.dataTask(with: request){(data, response, error)in if error == nil,
        let data = data,
        let response = response as? HTTPURLResponse{

        let decoder: JSONDecoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        do {

            let json = try decoder.decode(Store.self, from: data)


            self.store = [json]
            self.photo = json.photos

            DispatchQueue.main.async {
                self.nameLabel.text = json.name
                self.locationLabel.text = json.location
            }

        } catch {
            print("error:", error.localizedDescription)

        }

        }

        }.resume()

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    //UIView Corner redius
    let uiViewPath = UIBezierPath(roundedRect: storePhotoUIView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 8, height: 8))
    let uiViewMask = CAShapeLayer()
    uiViewMask.path = uiViewPath.cgPath
    storePhotoUIView.layer.mask = uiViewMask
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return photo?.count ?? 0
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


    let imageCell : UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath)
    let imageView = imageCell.contentView.viewWithTag(1) as! UIImageView

    print("asssss")

    let imageURL = URL(string:  "http://127.0.0.1:8000/photos/" + photo![indexPath.row].path)
    if imageURL == nil {
        print("nil")
    }else{
        DispatchQueue.global().async {
            let data = try? Data(contentsOf: imageURL!)
            if let data = data{
                let image = UIImage(data: data)
                DispatchQueue.main.async {
                    imageView.image = image
                }
            }
        }
    }
    return imageCell
}

}

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
Alex
  • 71
  • 2
  • 9

3 Answers3

1

you forget to refresh your collectionview, initially create the object for your collectionview

@IBOutlet weak var yourcollectionView: UICollectionView!

secondary on your main thread UI updation , refresh UICollectionView

DispatchQueue.main.async {
            self.nameLabel.text = json.name
            self.locationLabel.text = json.location
            yourcollectionView.reloadData()

        }

finally image loading from server , inhere you are doing the main thread call, it will freeze your app, for image showing process see this example

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
0

After calling dispatchque, try to add .resume()

DispatchQueue.global().async {
        let data = try? Data(contentsOf: imageURL!)
        if let data = data{
            let image = UIImage(data: data)
            DispatchQueue.main.async {
                imageView.image = image
            }
        }
    }.resume()
}
akaakoz
  • 248
  • 6
  • 16
0

If I were you instead of manually handling the response etc I would simply use an open source library https://github.com/onevcat/Kingfisher

The usage is simple enough that you won't have to handle these operations on your own:

imageView.kf.setImage(with: URL(string: "your_url_here"))
Ronak Khandelwal
  • 301
  • 2
  • 16