1

The instance I've successfully called the images from array JSON returned object the UICollection is very slow to load especially if it has main images.

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


    let childDict: NSDictionary = subCategoryData .object(at: indexPath.row) as! NSDictionary

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listcollectionview", for: indexPath) as! subCategoryCollectionViewCell

    subCategoryTable.register(UINib(nibName: "subCategoryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "listcollectionview")

    let subimages = childDict.object(forKey: "image") as! String!
    let data = NSData(contentsOf: NSURL(string: subimages!)! as URL)
    cell.backgroundImageView.image = UIImage(data: data! as Data)

    cell.categoryName.text = (subCategoryMenuData [indexPath.row] as? String)
    cell.categoryName?.textColor = UIColor.white
    cell.categoryName?.backgroundColor = UIColor().HexToColor(hexString: GREYBLACK)

    return cell;
}

I tried as well the dispatch.queue in didselectitemat when calling the segue but this didn't solve the problem

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let childDict: NSDictionary = subCategoryData .object(at: indexPath.row) as! NSDictionary

    if (childDict.object(forKey: "children") as! NSArray).count > 0{
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let initViewController: subCategory? = (sb.instantiateViewController(withIdentifier: "subCategory") as? subCategory)
        initViewController?.subCategoryData = (childDict.object(forKey: "children") as! NSArray)
        initViewController?.subName = childDict.object(forKey: "name") as! String!
        initViewController?.subId = childDict.object(forKey: "path") as! String!
        initViewController?.modalTransitionStyle = .flipHorizontal
        self.navigationController?.pushViewController(initViewController!, animated: true)
    }else{

        categoryName = childDict .object(forKey: "name") as! String
        categoryId = childDict .object(forKey: "path") as! String
        DispatchQueue.main.async {
            self.performSegue(withIdentifier: "productCategorySegue",sender: self)
        }
    }


}

It some times take 30 seconds to load

David Buik
  • 522
  • 1
  • 8
  • 31
  • 1
    `let data = NSData(contentsOf: NSURL(string: subimages!)! as URL)`, can you explain why you do that synchronously on the main thread, please? also it would be great to understand the idea behind registering nib _every time_ when you create a cell for the collection-view...? – holex Aug 13 '18 at 07:57
  • Using it to load the placeholder while all the images and page are loaded. – David Buik Aug 15 '18 at 00:43
  • where is the code what loads the image / page then? would you intend to share that with us too? – holex Aug 15 '18 at 07:14

4 Answers4

3

You load your image in cell for index you can use sdwebimage library install theough pods for lazy loading. It will definitely resolved your issue.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Anil Kumar
  • 1,830
  • 15
  • 24
2

Oh I just found the solutions thanks to @abhishekkharwar post here

I converted the ObjC to Swift 3 to resolve the issue.

DispatchQueue.global(qos: .default).async(execute: {() -> Void in
    var image = UIImage(contentsOfFile: frontPath)
    DispatchQueue.main.async(execute: {() -> Void in
        frontButton.setBackgroundImage(image, for: .normal)
    })
})
David Buik
  • 522
  • 1
  • 8
  • 31
0

Using AlamofireImage library:

let subimages = childDict.object(forKey: "image") as! String!
if let imageUrl = URL(string: subimages){
     cell.backgroundImageView.af_setImage(withURL: imageUrl, placeholderImage: nil)
}
Moayad Al kouz
  • 1,342
  • 1
  • 9
  • 19
0

-----Swift 4-----

Step 1: Add this Extension : if you dont know about extension , check this : Swift extension example

 extension UIImageView {
        func downloadImage(from url:String){

            if url != ""{
            let urlRequest = URLRequest(url: URL(string:url)!)

            let task = URLSession.shared.dataTask(with: urlRequest){(data,response,error) in

                if error != nil{
                    return
                }
                DispatchQueue.main.async {
                    self.image = UIImage(data: data!)
                }
            }
            task.resume()
            }
        }
    }

Step 2 : Using UIImageViewExtension for Downloading Image : In your 'cellForItemAt indexPath' method use this code :

cell.backgroundImageView.downloadImage(from: data)

Additional: check your image file size. if it is big in size thats obiously takes time to load . You can add this smooth image appearing animation before your image load for making it cool.

UIView.transition(with: cell.backgroundImageView,
                              duration: 0.5,
                              options: .transitionCrossDissolve,
                              animations: { cell.backgroundImageView.downloadImage(from: data) },
                              completion: nil) 
Nahid Raihan
  • 957
  • 1
  • 10
  • 20