繁体   English   中英

从alamofire swift的tableview单元格中加载来自url的图像

[英]load image from url in tableview cell from alamofire swift

我正在尝试使用Alomofire和swiftyJSON从json加载图像。 Json是字典:

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

Alamorefire和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"

如果有人可以帮忙吗? 如果有另一种方式随意写。

如果您使用的是Alamofire ,请尝试AlamofireImage 但是直接在uiimageview上使用af_快捷方式。 自动您将获得缓存,占位符图像,并且如果您使用可以回收单元格的表视图,则可以取消未完成的请求。

通过指定占位符图像,图像视图使用占位符图像,直到下载远程图像。

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

我分享了使用Swift 3AlamofireImage实现的代码:

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
 }
}

此外,您将需要Cocoapods

platform :ios, '10.0'

inhibit_all_warnings!
use_frameworks!

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

官方文档AlamofireImageImageCell.swift示例

从alamofire swift3的tableview单元格中的url加载图像: -

//你需要安装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)
                                 }                
                         }
                 }

我建议使用不同的库来加载图像。 我们总是在我们的项目中这样做。

有一个简单而智能的库,可以处理从缓存到占位符图像的所有内容。

它的名字是Kingfisher https://github.com/onevcat/Kingfisher

您可以使用JSON中的URL直接在ImageView上使用它:

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

这是最基本的异步图像加载方法,

看看你自己:)

如果您已经使用Alamofire ,你可以尝试AlamofireImage这是一个图像组件库Alamofire

然后,像这样完成提取图像:

import AlamofireImage

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

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

熊一起说你可以用AlamofireImage,

https://github.com/Alamofire/AlamofireImage

我为Swift 3做了这个,希望它可以帮助:

在控制器中实现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
}

在我的NetworkService中(我使用共享实现单例,它就像getInstance)我实现了调用AlamofireImage的requestImage函数:

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)
        }
    })
}

正如您所看到的,我使用GCD作为主队列来管理completionHandler,以确保它是处理视图修改的主队列。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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