Home > other >  load image from API in collection view (array of image url)
load image from API in collection view (array of image url)

Time:08-30

import UIKit

struct Welcome: Decodable {
    let images: [Location]
}

struct Location: Decodable {
    let imageloc: String
}

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    var imageloc = [Welcome]()
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageloc.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
        let url = URL(string: "http://swaminarayanwales.org.uk/DailyDarshan/ExportJsonV2.php?sMandir=Nairobi-Temple&Target=real&sm=sm)")
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if let error = error {
                print(error)
                return
            }
                do{
                    let jsonData = try JSONDecoder().decode(Welcome.self, from: data!)
                    if let imgUrl = URL(string: jsonData.images[indexPath.row].imageloc){
                        if let data = try? Data(contentsOf: imgUrl){
                            cell.imageView.image = UIImage(data: data)
                        }
                    }
                    DispatchQueue.main.async {
                         self.collectionView.reloadData()
                    }
                }catch{
                    print("error occured")
                }
        }.resume()
        return cell
    }
}

i don't have xib i just have custom class of collectionViewCell

import UIKit

class CollectionViewCell: UICollectionViewCell {
     @IBOutlet weak var imageView: UIImageView!
}

this is my whole code for getting image from API

Api has an array of image Urls

t think my code has a problem in function named cellForRowAt there i am unable to use array

how can i use array in it

As far as i know i should also pass array in second function nut when i use it in decoder it shows that it should be decoder type how can i access member imageLoc of Location struct for loading image

this is my API = http://swaminarayanwales.org.uk/DailyDarshan/ExportJsonV2.php?sMandir=Nairobi-Temple&Target=real&sm=sm)

CodePudding user response:

You can try SDWebImage.

Please check : https://github.com/SDWebImage/SDWebImage

Method 1 :

imgView.sd_imageIndicator = SDWebImageActivityIndicator.gray imgView.sd_setImage(with: URL(string: urlString), placeholderImage: UIImage(named: "placeholder"))

Method 2 :

if let imgUrl = URL(string: url) { cell.imgMain.sd_setImage(with: URL(string: strUrl)) { (img, erroe, cache, url) in if let er = error { print(er.localizedDescription) }else { print("success") } } }

CodePudding user response:

You can use SDWebImage

  1. Install pod for SDWebImage : pod 'SDWebImage'

  2. Use some line of code to fetch your image

import SDWebImage

for indicator on your image

your_image_name.sd_imageIndicator = SDWebImageActivityIndicator.gray

fetch and show your server image on your image view

your_image_name.sd_setImage(with: URL(string: 'your_get_server_image'), placeholderImage:
UIImage(named: "your_place_holder_image_name"))
  • Related