ios - Swift MVC Json 解析

标签 ios swift swift3

我正在尝试从我的 uicollectionview 中的 json url 进行解析。有人可以告诉我我做错了什么吗?

这是我的模型

init(carDetailDictionary: [String: Any]){
    self.regno = carDetailDictionary["regno"] as? String
    self.vin = carDetailDictionary["vin"] as? String
    self.timeStamp = carDetailDictionary["timestamp"] as? String
    self.fuel = carDetailDictionary["fuel"] as? String
}

static func fetchJson() -> [CarDetail]
{

    var carDetail = [CarDetail]()

    let jsonUrl = URL(string: "https://gist.githubusercontent.com/sommestad/e38c1acf2aed495edf2d/raw/cdb6dfb85101eedad60853c44266249a3f4ac5df/vehicle-attributes.json")
    let task = URLSession.shared.dataTask(with: jsonUrl!) { (data, responce, error) in

        if error != nil{
            print("Error")
        } else {
            if let urlContent = data{

                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: AnyObject]
                    print(json)
                    for object in json!{
                        let newCar = CarDetail(carDetailDictionary: json!)
                        carDetail.append(newCar)
                    }
                } catch {
                    print("Json Loading error")
                }
            }
        }
    }
    return carDetail
}

查看

类 CarDetailCell:BaseCell {

var carDetail: CarDetail!{
    didSet{
        self.updateUI()
    }
}

func updateUI() {

    carImageView.image = UIImage(named: "volvo")
    regnoLabel.text = carDetail.regno
    vinLabel.text = carDetail.vin
    brandLabel.text = carDetail.fuel
    timeStampLabel.text = carDetail.timeStamp
}

这是我的 View Controller

var carDetails = CarDetail

override func viewDidLoad() {
    super.viewDidLoad()

    carDetails = CarDetail.fetchJson()

   }
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {


    return carDetails.count ?? 0

}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! CarDetailCell
    let car = carDetails[indexPath.row]
    cell.carDetail = car

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: 300)
}

最佳答案

设置数据并在下载完成后重新加载 tableView:

class CarDetailController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

var carDetails = [CarDetail]()

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Cars"
    collectionView?.backgroundColor = UIColor.white
    // Registring cellID
    collectionView?.register(CarDetailCell.self, forCellWithReuseIdentifier: "cellId")

    collectionView?.contentInset = UIEdgeInsetsMake(50, 0, 0, 0)
    collectionView?.scrollIndicatorInsets = UIEdgeInsetsMake(50, 0, 0, 0)
}

private func fetchJson() {      
    let jsonUrl = URL(string: "https://gist.githubusercontent.com/sommestad/e38c1acf2aed495edf2d/raw/cdb6dfb85101eedad60853c44266249a3f4ac5df/vehicle-attributes.json")
    let task = URLSession.shared.dataTask(with: jsonUrl!) { (data, responce, error) in

        if error != nil{
            print("Error")
        } else {
            if let urlContent = data{

                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: AnyObject]
                    print(json)
                    for object in json!{
                        let newCar = CarDetail(carDetailDictionary: json!)
                        self.carDetail.append(newCar)
                    }
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                } catch {
                    print("Json Loading error")
                }
            }
        }
    }
}

关于ios - Swift MVC Json 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42955502/

相关文章:

ios - ld : framework not found Box

在 NavigationController 中查看的 iOS 无效矩形

ios - 验证文本字段Swift 3

iphone - iOS 推送通知在我的设备上不起作用

c++ - libstdc++ 和 libstdc++6 有什么区别?

ios - iOS应用仍然可以定位iOS 6吗?

ios - 重大位置更改不适用于仅支持 Wifi 的设备

swift - Xcode 8.0 和 Swift 3.0 转换 : Looking for explanation for a particular conversion error

swift - Realm LazyFilterBidirectionalCollection 错误 Swift 3

ios - 在快速编译器代码生成中找不到 objective-c 桥接 header