提问人:Dylan 提问时间:6/10/2022 更新时间:6/10/2022 访问量:123
将 GIPHY 图像加载到表格视图中
Loading GIPHY Images into table view
问:
大家好,所以我正在尝试从 GIPHY API 加载所有 gif 图像,但我不断收到以下错误。
2022-06-09 10:39:12.255202-0700 GIPHY App[41186:1667340] [boringssl] boringssl_metrics_log_metric_block_invoke(153) Failed to log metrics
2022-06-09 10:39:12.356240-0700 GIPHY App[41186:1667113] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__SwiftValue 0x600001ec5020> valueForUndefinedKey:]: this class is not key value coding-compliant for the key url.'
下面是我编写的代码,用于尝试使用 alamofire 和 alamofireimages 将图像加载到表视图中。
import UIKit
import Alamofire
import AlamofireImage
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var giphyImage = [GiphyData]()
@IBOutlet weak var giphyTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
fetchGiphyData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return giphyImage.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! GiphyTableViewCell
let gif: GiphyData
gif = giphyImage[indexPath.row]
AF.request(gif.url).responseImage { response in
if let image = response.value {
cell.giphyImage.image = image
}
if case .success(let image) = response.result {
print("image downloaded: \(image)")
}
}
return cell
}
func fetchGiphyData() {
let request = AF.request("https://api.giphy.com/v1/gifs/trending?api_key=zONZGFIbbvYDBjLEBlgKxLjbsClfmptw&limit=25&rating=pg-13")
request.responseDecodable(of: GiphyResponseData.self) { (response) in
guard let gifs = response.value else { return }
let gifImages = [gifs]
for i in 0..<gifImages.count {
self.giphyImage.append(GiphyData(
url: ((gifImages[i] as AnyObject).value(forKey: "url") as! String)
))
}
self.giphyTableView.reloadData()
}
}
}
当我解析 JSON 信息时,我希望从 GiphyData 结构中获取 URL,但也许这是不正确的?我是自己尝试项目的新手,所以任何建议/帮助都很棒!
import UIKit
struct GiphyResponseData: Codable {
var data: [ImageInfo]
}
struct ImageInfo: Codable {
var images: ImageTypes
}
struct ImageTypes: Codable {
var original: GiphyData
}
struct GiphyData: Codable {
var url: String
}
谁能告诉我为什么错误不断弹出?我从fetchGiphyData函数中获取了我需要的URL,但表视图没有加载图像。
答: 暂无答案
评论
(gifImages[i] as AnyObject).value(forKey: "url")
let gifImages = [gifs]
for anImageInfo in gifs { let aGiphyData = anImageData.images.orignal; self.giphyImage.append(aGiphyData) }