Search code examples
iosswift3uicollectionviewalamofireimage

How to make images appear in the view with its labels in UICollectionView cells using Alamofire?


I'm making an app like the AppStore with UICollectionView so when downloading the data from url

import Alamofire
import AlamofireImage

class AppCategory: NSObject {
var id: NSNumber?
var title: String?
var apps: [App]?
var type: NSNumber?

static func fetchFeaturedApps(completionHandler: @escaping ([AppCategory]) -> ()) {

let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
var appCategories = [AppCategory]()
             let sections = OFFERIM["sections"] as! [Dictionary<String, AnyObject>]
            for i in 0..<sections.count {
                var appCategory = AppCategory()
                var apps = [App]()

                let sectionTitle = sections[i]["title"] as! String
                appCategory.title = sectionTitle
                let sectionType = sections[i]["type"] as! NSNumber
                appCategory.type = sectionType
                let sectionId = sections[i]["id"] as! NSNumber
                appCategory.id = sectionId
                // for Apps inside each section
                let lists = sections[i]["lists"] as! [String: AnyObject]
                 for j in 0..<lists.count{
                    let app = App()

                    let id = lists[j]["id"] as! NSNumber
                    app.id = id

                    let thumb = lists[j]["thumb"]! as! String

                    Alamofire.request(thumb).responseImage { response in

                        if let image = response.result.value {
                            app.image = image
                            print("image downloaded: \(image)")
                        }
                    }
                    let title = lists[j]["title"] as! String
                    app.title = title

                    apps.append(app)
                }
                appCategory.apps = apps
                appCategories.append(appCategory)
            }
            DispatchQueue.main.async(execute: {
                completionHandler(appCategories)
            })
        }catch{
            print("JSON Processing Failed")
        }
        }.resume()
}
}

and I have these classes as models

class App: NSObject {
var id: NSNumber?
var title: String?
var image: UIImage?

}

and I call featuredApps in the viewDidLoad in viewController what happened is when the view loaded the labels appears but the images not in the collection view .

I need to scroll each row to make the images appear.

and I don't kwon the problem where ???


Solution

  • Keep the url and set the url to image view use AlamofireImage.

    imageView.af_setImage(withURL: url)