如何解决解码REST时Swift Playground中出现奇怪错误
import Foundation
import Combine
let liveSample = URL(string: "https://newsapi.org/v2/top-headlines?country=us&apiKey=<api key>")!
struct ArticleList: Codable {
struct Article: Codable {
struct Source: Codable {
var id: String?
var name: String?
}
var source: Source?
var author: String?
var title: String?
var description: String?
var url: URL?
var urlToImage: URL?
var publishedAt: Date?
var content: String?
}
var status: String
var totalResults: Int
var articles: [Article]
}
struct Resource<T: Codable> {
let request: URLRequest
}
extension URLSession {
func fetchJSON<T: Codable>(for resource: Resource<T>) -> AnyPublisher<T,Error> {
return dataTaskPublisher(for: resource.request)
.map { $0.data }
.decode(type: T.self,decoder: JSONDecoder())
.erasetoAnyPublisher()
}
}
var subscriber: AnyCancellable?
var resource: Resource<ArticleList> =
Resource<ArticleList>(request: URLRequest(url: liveSample))
subscriber?.cancel()
subscriber = URLSession.shared.fetchJSON(for: resource)
.receive(on: dispatchQueue.main)
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
print("The publisher finished normally.")
case .failure(let error):
print("An error occured: \(error).")
}
},receiveValue: { result in
dump(result)
})
发生错误:typeMismatch(Swift.Double,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“ articles”,intValue:nil),_JSONKey(stringValue:“ Index 0”,intValue:0),CodingKeys (stringValue:“ publishedAt”,intValue:nil)],debugDescription:“预期对Double进行解码,但找到了一个字符串/数据。”,底层错误:nil))。
解决方法
我可以看到您在这里直接使用JSONDecoder()
,在您的模型中var publishedAt: Date?
是一个日期对象。
您需要先配置解码器以从字符串中解析日期,然后使用它。
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601 // <------- set date decoding strategy explicitly
extension URLSession {
func fetchJSON<T: Codable>(for resource: Resource<T>) -> AnyPublisher<T,Error> {
return dataTaskPublisher(for: resource.request)
.map { $0.data }
.decode(type: T.self,decoder: decoder)
.eraseToAnyPublisher()
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。