网址中的数据无法加载。虽然网址正确

时间:2019-12-08 10:21:14

标签: swift networking swift5

DispatchQueue.global().async{
        do{
            let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json")!
            let data = try Data(contentsOf: url)

            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601


            let downloadedFriends = try decoder.decode([Friend].self, from: data)

            DispatchQueue.main.async {
                self.friends = downloadedFriends
                self.tableView.reloadData()
            }
        }catch{
            print(error.localizedDescription)
        }
    }
  

打印:“由于缺少数据,无法读取数据。”   我检查了网址https://stats.stackexchange.com/questions/262046/probability-of-gaussian-being-smaller-than-multiple-other-gaussians,这是正确的

2 个答案:

答案 0 :(得分:0)

我认为问题出在您的Friend结构中。您需要检查每个字段是否正确。尽管我强烈建议使用app.quicktype.io自动生成可编码结构

这里的朋友结构正确:


// MARK: - Friend
struct Friend: Codable {
    var id: String?
    var isActive: Bool?
    var name: String?
    var age: Int?
    var company, email, address, about: String?
    var registered: Date?
    var tags: [String]?
    var friends: [FriendElement]?
}

// MARK: - FriendElement
struct FriendElement: Codable {
    var id, name: String?
}

答案 1 :(得分:0)

Shynggys,我现在也正在使用JSONDecoder,并将您的代码与我的代码进行了比较。我在DispatchQueue类的async方法中对您的代码进行了少量更改,并从URL返回了数据。屏幕打印中的第30行。

我还使用了David建议的Friend结构,因为您没有在帖子中包含所有代码。

import UIKit

struct Friend: Codable {
    var id: String?
    var isActive: Bool?
    var name: String?
    var age: Int?
    var company, email, address, about: String?
    var registered: Date?
    var tags: [String]?
    var friends: [FriendElement]?
}

// MARK: - FriendElement
struct FriendElement: Codable {
    var id, name: String?
}

DispatchQueue.global().async{
    do{
        let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json")!
        let data = try Data(contentsOf: url)

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601

        let downloadedFriends = try decoder.decode([Friend].self, from: data)

        DispatchQueue.main.async {
            let friends = downloadedFriends //remove self, and assign to friends
//            self.tableView.reloadData()
            print (friends)
        }
    }catch{
        print(error.localizedDescription)
    }
}

控制台结果

enter image description here