Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
swift json帮助在表视图控制器上显示数据_Json_Swift_Xcode_Tableview_Codable - Fatal编程技术网

swift json帮助在表视图控制器上显示数据

swift json帮助在表视图控制器上显示数据,json,swift,xcode,tableview,codable,Json,Swift,Xcode,Tableview,Codable,我的api模型结构这是我从quickTypeIo api生成器中使用的 // my url // https://fetch-hiring.s3.amazonaws.com/hiring.json /* my json [ {"id": 383, "listId": 4, "name": ""}, {"id": 472, "listId": 1, "name": ""}, {"id": 625, "listId": 2, "name":

我的api模型结构这是我从quickTypeIo api生成器中使用的

// my  url
   //  https://fetch-hiring.s3.amazonaws.com/hiring.json
    /*
    my json 
    [
    {"id": 383, "listId": 4, "name": ""},
    {"id": 472, "listId": 1, "name": ""},
    {"id": 625, "listId": 2, "name": null}
    ]
   */
// my main vc class for table view controller 

import UIKit
class HeadlLinesTableViewController: UITableViewController {
      var parse = [HiringElement]()

    override func viewDidLoad() {

        // Do any additional setup after loading the view.


        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let urlString =  "https://fetch-hiring.s3.amazonaws.com/hiring.json"
        guard let url = URL(string: urlString) else { return }

        // 2
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error!.localizedDescription)
            }

            guard let data = data else { return }
            // 3
            //Decode data

            self.Elements = try? JSONDecoder().decode(HiringElement.self, from: data)

            print(data)

            // 4
            //Get back to the main queue
            DispatchQueue.main.async  {
                self.tableView.reloadData()
            }
            // 5
            }.resume() // fires of request

    }
在这里,我的表视图控制器方法无法在上显示数据,还有一些错误。我使用的是tableview控制器,所以不需要tableview委托或数据源

struct HiringElement: Codable {
    let id, listID: Int
    let name: String?

    enum CodingKeys: String, CodingKey {
        case id
        case listID
        case name
    }
} typealias Hiring = [HiringElement]
这是我的表格视图单元类

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        guard let articles = Elements else { return 0 }

        return   return parse.count

    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

            as? newsTableViewCell else {
              fatalError(" cell not found ")  }

        // here I have errors thanks 

           cell.titleLabel.text = parse[indexPath.row].name
    print(cell.titleLabel.text)


        return cell
    }

}

我想你应该做解码部分。以下是一个解决方案:

import UIKit

class newsTableViewCell: UITableViewCell {
    //var article:Article!
    @IBOutlet weak var avator: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var newsLabel: UILabel!



    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

    }


}
struct HiringElement:可解码{
let id,listId:Int
名称:字符串?
}
@房地产经纪人
结构IgnoreFailure:可解码{
var wrappedValue:[值]=[]
私有结构_None:可解码{}
init(来自解码器:解码器)抛出{
var container=try decoder.unkeydcontainer()
while!container.isattend{
如果let decoded=try?container.decode(Value.self){
wrappedValue.append(已解码)
}
否则{
try?container.decode(_None.self)
}
}
}
}
然后在headlinestablevewcontroller.swift中编写以下代码

struct HiringElement: Decodable {
    let id, listId: Int
    let name: String?
}

@propertyWrapper
struct IgnoreFailure<Value: Decodable>: Decodable {
    var wrappedValue: [Value] = []

    private struct _None: Decodable {}

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        while !container.isAtEnd {
            if let decoded = try? container.decode(Value.self) {
                wrappedValue.append(decoded)
            }
            else {
                try? container.decode(_None.self)
            }
        }
    }
}
typealias ArrayIgnoringFailure=IgnoreFailure
然后尝试解码为:

typealias ArrayIgnoringFailure<Value: Decodable> = IgnoreFailure<Value>
guard let objects=try?JSONDecoder().decode(ArrayIgnoringFailure.self,from:data)else{return}
self.elements=objects.wrappedValue

希望它能解决您的问题。

我想我对代码做了一点修改,现在没有错误了,我看到了json中的字节数据,但在编译器或表视图中看不到任何数据。看到这个问题,试着联系一下。我不确定我哪里搞砸了,但我从api生成器quick type io中创建了json模型,但我保持了模型的简单性,就像这样。struct HiringElement:Codable{let id,listID:Int let name:String?我认为JSON中的“listID”和codingKey“listID”是不同的。这就是问题所在。是的,让我试试。非常感谢你,如果你能向我解释你的struct ignore failure方法和解码方法,并键入别名,谢谢@ubaiat Jahan mumumu
guard let objects =  try? JSONDecoder().decode(ArrayIgnoringFailure<HiringElement>.self, from: data)  else { return }
self.elements = objects.wrappedValue