简体   繁体   中英

load image from url in tableview cell from alamofire swift

I am trying to load image from json using Alomofire and swiftyJSON. Json is dictionary:

{"name": {"image": "https://...",}}

Alamorefire and SwiftyJSON

var imageLoad: String!

Alamofire.request(.GET, url).responseJSON { (response) -> Void in
    if let value = response.result.value {
    let json = JSON(value)

    if let jsonDict = json.dictionary {

        let image = jsonDict["name"]!["image"].stringValue
        print(image) // https://....
        self.imageLoad = image        
    }
    self.tableView.reloadData()
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TVCell

// Configure the cell...

cell.imageTableView.image = UIImage(named: imageLoad) // not working "fatal error: unexpectedly found nil while unwrapping an Optional value"

If anyone can help? If there is another way feel free to write.

If you are using Alamofire , try AlamofireImage . But use the af_ shortcuts directly on uiimageview. Automatically you will get caching, placeholder images, and you can cancel outstanding requests if you are using a table view which could recycle the cells.

By specifying a placeholder image, the image view uses the placeholder image until the remote image is downloaded.

let imageView = UIImageView(frame: frame)
let url = URL(string: "https://httpbin.org/image/png")!
let placeholderImage = UIImage(named: "placeholder")!

imageView.af_setImage(withURL: url, placeholderImage: placeholderImage)

https://github.com/Alamofire/AlamofireImage

I share a code implemented using Swift 3 and AlamofireImage :

import UIKit
import AlamofireImage

class MovieViewCell: UICollectionViewCell {

@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var posterView: UIImageView!

 func configure(for movie: Movie) {
    titleLabel.text = movie.title
    overviewLabel.text = movie.overview

    let url = URL(string: movie.poster_path!)!
    posterView.af_setImage(withURL: url)
 }

 override func prepareForReuse() {
    super.prepareForReuse()

    posterView.af_cancelImageRequest()
    posterView.image = nil
 }
}

Also, you will need Cocoapods :

platform :ios, '10.0'

inhibit_all_warnings!
use_frameworks!

target 'MovieApp' do
  pod 'Alamofire', '~> 4.5'
  pod 'AlamofireImage', '~> 3.3'
end

Official documentation AlamofireImage and an ImageCell.swift example

load image from url in tableview cell from alamofire swift3 : -

//you need install pod 'AlamofireImage', '~> 3.0' pod

    import Alamofire
    import AlamofireImage

// put into cellForRowAt

    Alamofire.request(self.profileImgArr[indexPath.row]).responseData { (response) in
                    if response.error == nil {
                             print(response.result)

                             // Show the downloaded image:
                             if let data = response.data {
                                     cell.profileImg.image = UIImage(data: data)
                                 }                
                         }
                 }

I recommend using a different library for loading the images. We always do this in our projects.

There is an easy and smart library which handles pretty much everything from caching to placeholder image.

It's name is Kingfisher https://github.com/onevcat/Kingfisher

You can use it directly on the ImageView with the URL from JSON Example:

let url = URL(string: "url_of_your_image")
imageView.kf.setImage(with: url)

This is the most basic Asynchronous image loading method,

Take a look for yourself :)

If you're already using Alamofire , you can try AlamofireImage which is an image component library for Alamofire .

Then, fetching image is done like this:

import AlamofireImage

Alamofire.request(.GET, "https://httpbin.org/image/png")
         .responseImage { response in

             if let image = response.result.value {
                 print("image downloaded: \(image)")
             }
         }

As Bear with me said you can use AlamofireImage,

https://github.com/Alamofire/AlamofireImage

I made this for Swift 3, hope it can help:

In the controller implementing the tableViewDataSource

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Cell
    NetworkService.shared.requestImage(path: path, completionHandler: {image in
            cell.photo?.image = image
        })
    }
    return cell
}

In my NetworkService (I use the shared to implement singleton, it's like getInstance) I implemented the requestImage function calling AlamofireImage:

func requestImage(path: String, completionHandler: @escaping (Image) -> Void){
    Alamofire.request("\(path)").responseImage(imageScale: 1.5, inflateResponseImage: false, completionHandler: {response in
        guard let image = response.result.value else{
            print(response.result)
            return
        }
        DispatchQueue.main.async {
            completionHandler(image)
        }
    })
}

As you can see I use the GCD for main queue to manage the completionHandler just to be sure that it is the main queue which handles the view modification.

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