gpt4 book ai didi

ios - Swift:使用字典将 alamofire 中的 JSON 数据解析为数组时出错

转载 作者:行者123 更新时间:2023-11-28 07:35:55 25 4
gpt4 key购买 nike

我有以下 JSON 响应,我想获取 idurl

[
{
"albumId": 1,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
}]

在 View Controller 中,我的编码如下。

import UIKit
import Alamofire
import SDWebImage


class AlbumResponse: Codable {
var list: Int
var hits: [Album]
}


class Album: Codable {
var id: Int
var title : String
var url: String
var thumbnailUrl : String
}



class CollectionView: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

let url1 = ["JSON URL"]
@IBOutlet weak var collection: UICollectionView!
var arrList = [Album]()


override func viewDidLoad() {
super.viewDidLoad()
reequest()
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.collection.reloadData()

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrList.count

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell: firstCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! firstCollectionViewCell
let objct = arrList[indexPath.row]
cell.label.text = String(objct.id)
cell.img!.sd_setImage(with: URL(string: objct.url), placeholderImage: #imageLiteral(resourceName: "download"), options: .retryFailed, completed: nil)

return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

let width = (self.view.frame.size.width - 5 * 2 ) / 2 //some width
let height = width * 1.45 //ratio
return CGSize(width: width, height: height)
}


func reequest() {

let url = URL(string: "JSON URL")
Alamofire.request(url!).responseJSON {(response) in

switch (response.result){
case .success:
if let data = response.data {
do {
let response = try JSONDecoder().decode(AlbumResponse.self, from: data)
self.arrList = response.hits
DispatchQueue.main.async {
self.collection.reloadData()
}
} catch {
print(error.localizedDescription)
}
}

case .failure(let error):
print("error to print the data \(error)")
}
}

}
}

运行时黑屏

最佳答案

实际上,就像 Scrpitable 所说的那样,黑屏可能与您的代码无关。例如,每当我遇到黑屏时,我首先要检查的是“Is Initial View Controller”是否针对我的一个 View 进行了检查。有时,如果我忘记设置初始 View ,它只会显示黑屏。我会为我的意思添加一个屏幕截图。 enter image description here

关于ios - Swift:使用字典将 alamofire 中的 JSON 数据解析为数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53173150/

25 4 0
文章推荐: javascript - 是什么导致了这个 JS 控制台错误?
文章推荐: javascript - 使用 JavaScript 在
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com