简体   繁体   中英

Download images using Alamofire and display in UITableViewCell

I have these two functions:

func callAlamo(url: String){
    Alamofire.request(url).responseJSON(completionHandler: {
        response in

        self.parseData(JSONData: response.data!)

    })
}

func parseData(JSONData: Data) {
    do {
        var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard
        if let tracks = readableJSON["tracks"] as? JSONStandard{
            if let items = tracks["items"] as? [JSONStandard]{
                for i in 0..<items.count{
                    let item = items[i]
                    let name = item["name"] as! String

                    if let album = item["album"] as? JSONStandard{
                        if let images = album["images"] as? [JSONStandard]{
                            let imageData = images[0]
                            let mainImageUrl = URL(string: imageData["url"] as! String)
                            let mainImageData = NSData(contentsOf: mainImageUrl!)

                            let mainImage = UIImage(data: mainImageData as! Data)
                            posts.append(post.init(image: mainImage, name: name))

                            self.tableView.reloadData()
                        }
                    }
                }
            }
        }
    }
    catch{
        print(error)
    }
}

That retrieve song information from Spotify using alamofire. These functions are set up inside of a UITableViewController class. I have a separate UITableViewCell class set up in the same file where I set up this image:

let albumCoverImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.translatesAutoresizingMaskIntoConstraints = false

    return imageView
}()

How would I use get the retrieved information from the two functions into that image? Because I cannot access the functions from inside the image imitation.

Use "SDWebImage" library for downloading images asynchronously.

Refer below link :-

https://github.com/rs/SDWebImage

Usage :-

Objective-C:

#import <SDWebImage/UIImageView+WebCache.h>
[imageView sd_setImageWithURL:[NSURL 
URLWithString:imageURL]
         placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Swift:

import SDWebImage

imageView.sd_setImage(with: URL(string: imageURL), placeholderImage: UIImage(named: "placeholder.png"))
var imgFinal = [String:UIImage]()

Store your images in "imgFinal" array in func parseData():

self.imgArrList[i] = imageData["url"]


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


  let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CategoryTableViewCell
    load_image((imgArrList[indexPath.row] as? String)!, imageview: cell.titleImage, indVal: indexPath.row)
return cell
}

Add this method to download image:

func load_image(link:String, imageview:UIImageView, indVal:Int)
{

    let url:NSURL = NSURL(string: link)!
    let session = NSURLSession.sharedSession()

    let request = NSMutableURLRequest(URL: url)
    request.timeoutInterval = 10

    let task = session.dataTaskWithRequest(request) {
        (
        let data, let response, let error) in

        guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {

            return
        }

        var image = UIImage(data: data!)

        if (image != nil)
        {
            func set_image()
            {
                //self.images_cache[link] = image
                self.imgFinal[link] = image
                imageview.image = image
            }
            dispatch_async(dispatch_get_main_queue(), set_image)
        }
    }
    task.resume()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM