我正在爲iOS應用程序構建帶有遠程數據的表視圖。我正在使用AlamoFire和SwiftyJSON來加載一個JSON文件和一些劇集。使用Alamofire從JSON中使用URL加載圖像
的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)
}
這將加載圖像,但該表的看法是超級慢。但是,不使用contentsOf:URL違背其加載與alamofire數據帶來的好處(我相信這就是爲什麼該表是如此緩慢,當我上下滾動)?
我不應該被異步加載圖像?如果是這樣,我是否爲每個圖像製作一個單獨的Alamofire.request?
我發現教程下載具有Alamofire數據,以及其他加載圖像(但沒有別的),但如果我想加載數據,並載入圖像去與這些數據呢?
感謝您提供的任何幫助。
謝謝,真是棒極了! :d – cesarcarlos