【发布时间】:2017-05-24 15:59:27
【问题描述】:
我正在为 iOS 应用程序构建一个包含远程数据的表视图。我正在使用 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”替换为
// 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)
}
这会加载图像,但表格视图非常慢。但是,不使用 contentsOf: url 是否违背了使用 alamofire 加载数据的好处(我相信这就是为什么我上下滚动时表格如此缓慢的原因)?
我不应该异步加载图像吗?如果是这样,我是否要为每张图片单独创建一个 Alamofire.request?
我找到了使用 Alamofire 加载数据的教程,以及其他加载图像的教程(但没有其他内容),但是如果我想加载数据并加载图像以配合该数据怎么办?
感谢您提供的任何帮助。
【问题讨论】:
标签: ios json alamofire image-loading