FetchJson无缘无故地停止了工作

时间:2019-05-07 09:22:51

标签: ios json swift rest codable

我正在从新闻API获取数据。一切都运转了40多次,然后发生了什么事,却没有任何反应。第二天我打开Mac后,它工作了好几次,但现在又没有了,我不知道为什么会这样。请帮忙,代码如下:

我试图重新安装Xcode,管理一些plist,重写项目。

struct Model: Codable {
    let articles: [News]
}

struct Source: Codable {
    var name: String?
    var id: String?
}

struct News: Codable {
    var title: String?
    var url: String
    var description: String
    var urlToImage: URL?
    var source: Source
    var publishedAt: String?
    var author: String?
    var content: String?
}


class myData {
    static func getData(completion: @escaping ([News]) -> ()) {
        DispatchQueue.global(qos: .userInteractive).async {
            var finalData = [News]()

            let jsonUrlString = "https://newsapi.org/v2/top-headlines?country=ua&apiKey=0cff1368c1d1445d9a0bccb6063a5220"
            if let url = URL(string: jsonUrlString) {
                if let data = try? Data(contentsOf: url) {

                    let decoder = JSONDecoder()
                    if let jsonPetitions = try? decoder.decode(Model.self, from: data) {
                        finalData = jsonPetitions.articles
                    }
                }
            }
            DispatchQueue.main.async {
                completion(finalData)
            }
        }
    }
}

我的代码正在重新加载tableView,并且每次都为空。它应该看起来像简单的json。

1 个答案:

答案 0 :(得分:0)

您有解码错误。如果遇到解码错误,将很容易推论。您回复中的新闻源之一的description属性为null。只需使其Optional即可。

尝试一下:

struct Model: Codable {
    let articles: [News]
}

struct Source: Codable {
    var name: String?
    var id: String?
}

struct News: Codable {
    var title: String?
    var url: String
    var description: String?
    var urlToImage: String?
    var source: Source
    var publishedAt: String?
    var author: String?
    var content: String?
}


class MyData {
    static func getData(completion: @escaping ([News]) -> ()) {
        DispatchQueue.global(qos: .userInteractive).async {
            var finalData = [News]()

            let jsonUrlString = "https://newsapi.org/v2/top-headlines?country=ua&apiKey=0cff1368c1d1445d9a0bccb6063a5220"
            if let url = URL(string: jsonUrlString) {

                do {
                    let data = try? Data(contentsOf: url)

                    let decoder = JSONDecoder()
                    let jsonPetitions = try decoder.decode(Model.self, from: data!)
                    finalData = jsonPetitions.articles
                } catch {
                    print(error)
                }


            }
            DispatchQueue.main.async {
                completion(finalData)
            }
        }
    }
}

MyData.getData { (news) in
    print(news)
}