ios - 使用 Alamofire 使用来自 JSON 的 URL 加载图像

标签 ios json alamofire image-loading

我正在为 iOS 应用构建一个包含远程数据的 TableView 。我正在使用 AlamoFire 和 SwiftyJSON 加载包含一系列剧集的 JSON 文件。

JSON 文件的结构如下:

{
  "id": "456",
  "name": "EpOne",
  "description": "Episode description 1",
  "imageURL": "http://myimage.com/myimagefile1.jpg"
},
{
  "id": "789",
  "name": "Eptwo",
  "description": "Episode description 2",
  "imageURL": "http://myimage.com/myimagefile2.jpg"
} ...

所以我打电话

getEpisodes(url: endpoint)

来自 ViewDidLoad。这将运行以下内容:

func getEpisodes(url: String) {
    Alamofire.request(url, method: .get).validate().responseJSON { response in
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            self.buildEpisodeArray(json: json)

        case .failure(let error):
            print(error)
        }
    }
}

func buildEpisodeArray(json: JSON) {
    if let allEpisodes = json["episodes"].array {
        for singleEpisode in allEpisodes {
            let currentEpisode = Episode()
            currentEpisode.name = singleEpisode["name"].string!
            currentEpisode.imageURL = singleEpisode["imageURL"].string!
            episodes.append(currentEpisode)
        }
    }
    tableView.reloadData()
}

然后我将数据加载到我的单元格中

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellIdentifier = "Cell"
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! EpisodeCell
    cell.nameLabel.text = episodes[indexPath.row].name

    // TODO Get the image

    return cell
}

此时一切正常。问题是当我尝试加载图像时。我已经检查了一些教程(我对此有点陌生),在使用 Alamofire 获取数据后,他们使用 contentsOf: url 来获取图像。因此,就我而言,我会将“//TODO 获取图像”替换为

// Get the image
    if let url = NSURL(string: episodes[indexPath.row].imageURL),
        let data = NSData(contentsOf: url as URL) {
        cell.episodeImage.image = UIImage(data: data as Data)
    }

这会加载图像,但表格 View 非常慢。但是,使用 contentsOf: url 不会违背使用 alamofire 加载数据的好处(我相信这就是为什么当我上下滚动时表格如此缓慢的原因)?

我不应该异步加载图像吗?如果是这样,我是否为每张图片制作一个单独的 Alamofire.request?

我找到了使用 Alamofire 加载数据的教程,以及其他加载图像的教程(但没有别的),但是如果我想加载数据并加载图像以配合该数据怎么办?

感谢您提供的任何帮助。

最佳答案

我建议您使用 SDWebImage,它还可以开箱即用地处理图像缓存: https://github.com/rs/SDWebImage

基本上很容易使用:

import SDWebImage

// Get the image
cell.episodeImage.sd_setImage(with: URL(string: episodes[indexPath.row].imageURL))

关于ios - 使用 Alamofire 使用来自 JSON 的 URL 加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44163343/

相关文章:

swift - 阿拉莫菲尔 4 请求开放天气

ios - 我正在显示诸如 Expendable Tableview 之类的数据

ios - 这些动画使用了哪些技术?

json - 如何使用node js同步读取sqlite3数据库?

javascript - 当 ID 不同时将各个对象打印到 DOM

iOS 11 服务器交互

ios - 钥匙串(keychain)数据存储在哪里?

ios - 在应用程序中使用相同的 Apple 帐户但使用不同的用户帐户时禁用恢复 IAP

java - 如何将此 JSON 响应解析为 POJO

ios - 使用 Alamofire 和 Argo : Could not find member 'None'