-1

I'm using Alamofire to fetch data from server and then put them in an array of CarType objects which CarType is my struct. what I get from server is name , id and iconUrl. from iconUrls i want to download icons and put them in icon. after that I'll use icon and name in a collection view. my Alamofire request is:

var info = [CarType]()
Alamofire.request(.GET,"url")
    .responseJSON { response in
        for (_,subJson):(String, JSON) in json["result"]
        {
            let name = subJson["name"].string
            let iconUrl = subJson["icon"].string
            let id = subJson["id"].int
            info.append(CarType(id: id!, name: name!, iconUrl: iconUrl! , image: UIImage()))
        }

my struct is:

import Foundation
import UIKit

struct CarType {
    var name : String
    var id : Int
    var iconUrl : String
    var icon : UIImage
}

I want to download images before using them in collectionView. How can i download images (using AlamofireImage) and put them in related carType icon property?

Hos Ap
  • 1,168
  • 2
  • 11
  • 24

2 Answers2

2

What you are asking is really bad practice in mobile app. Just a case, for example, you made a request and got like 20 items in an array, and in order to put all UIImages in your models, you have to make 20 more requests, also you even don't know if your users will eventually use (view) those icons or no.

Instead, you could fetch the images when the cell (I guess, you will be displaying those icons in a cell) is displayed, for this purpose you could use libs like SDWebImage(objective c) or Kingfisher(swift) which have extensions for UIImageView to make it simple to fetch and display image on. Those libs can also cache the downloaded image.

Also, another suggestion for object mapping. Currently, you are mapping json to your model manually. There are a lot of good libs to handle that for you, which could automate your object mapping process, for example - ObjectMapper

Hope, this was helpful. Good Luck!

Fahri Azimov
  • 11,470
  • 2
  • 21
  • 29
1

I have done functionalities thing in UITableview, added following in CellForRowIndex method:

getDataFromUrl(urlString){(data,response,error) -> Void in
                    if error == nil {
                        // Convert the downloaded data in to a UIImage object
                        let image = UIImage(data: data!)
                        // Store the image in to our cache
                        if((image) != nil){
                            // Store the image in to our cache
                            self.imageCacheProfile[urlString] = image
                            // Update the cell
                            DispatchQueue.main.async(execute: {
                                cell.imgvwProfile?.image = image
                            })
                        }
                        else{
                            cell.imgvwProfile!.image = UIImage(named: "user")
                        }
                    }
                }

func getDataFromUrl(_ strUrl:String, completion: @escaping ((_ data: Data?, _ response: URLResponse?, _ error: NSError? ) -> Void)) {
    let url:URL = URL(string: strUrl)!
    let request = URLRequest(url: url)

    URLSession.shared.dataTask(with: request) {data, response, err in
        print("Entered the completionHandler")
        }.resume()

}

You also need to declare imageCache to store downloaded images.

var imageCache = [String:UIImage]()

You can use above code in your method and it should work just.

pankaj
  • 7,878
  • 16
  • 69
  • 115