【发布时间】:2021-03-03 10:34:39
【问题描述】:
当尝试从我的 GitHub 空间上的 json 读取数据时,我得到一个错误
nw_protocol_get_quic_image_block_invoke dlopen libquic 失败 来自服务器的无效响应。请重试。
是我使用了错误的 url 还是我解析数据的方式有问题?
我的仓库地址
https://github.com/stark226/stark226.github.io.git
这个url有一个简单的json文件
https://github.com/stark226/stark226.github.io/blob/3b2bebb4a3d85524732c7e7ec302b24f8d3e66ae/testjson.json
在我看来Didload
getDataFromJsonOnGithub(completed: { [weak self] result in
guard let self = self else {return}
switch result {
case .success(let expected):
print(expected)
case .failure(let error):
print(error.rawValue)
}
})
我的结构
struct RemoteData: Codable, Hashable {
var tokenDuration: Int
}
我的功能
func getDataFromJsonOnGithub(completed: @escaping (Result<RemoteData, ListOfErrors>) -> Void) {
let endpoint = "https://github.com/stark226/stark226.github.io/stark226/testjson.json"
guard let url = URL(string: endpoint) else {
completed(.failure(.invalidUsername))
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let _ = error {
completed(.failure(.unableToComplete))
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
completed(.failure(.invalidResponse))
return
}
guard let data = data else {
completed(.failure(.invalidData))
return
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let expectedRrsult = try decoder.decode(RemoteData.self, from: data)
completed(.success(expectedRrsult))
} catch {
completed(.failure(.invalidData))
}
}
task.resume()
}
enum ListOfErrors: String, Error {
case invalidUsername = "This username created an invalid request. Please try again."
case unableToComplete = "Unable to complete your request. Please check your internet connection"
case invalidResponse = "Invalid response from the server. Please try again."
case invalidData = "The data received from the server was invalid. Please try again."
case unableToFavorite = "There was an error favoriting this user. Please try again."
case alreadyInFavorites = "You've already favorited this user. You must REALLY like them!"
}
【问题讨论】:
-
您必须访问原始文件。您正在访问的页面是 HTML 页面。尝试以下网址(点击 GitHub 中的 Raw 按钮):raw.githubusercontent.com/stark226/stark226.github.io/…
-
我怎样才能做到这一点?
-
使用正确的 url 或任何返回 JSON 的 url。我已经发过了。
-
谢谢!没有看到更新,它正在工作!如果您想将此作为答案,我可以将其检查为已解决
-
为什么是
weak self - guard跳舞?self没有在闭包中使用。即使使用了self,Swift 中也存在可选链接(self?.doSomething())。并且强烈建议您不要忽略 real DecodingError。.invalidData毫无意义