【发布时间】:2020-07-21 17:02:59
【问题描述】:
我正在尝试了解进行 JSON 网络调用的组合方法。我是 显然缺少一些基本的东西。
我得到的最接近失败,取消了 URLSession。
class NoteDataStore: ObservableObject {
@Published var notes: [MyNote] = []
init() {
getWebserviceNotes()
}
func getWebserviceNotes() {
let pub = Webservice().fetchNotes()
.sink(receiveCompletion: {_ in}, receiveValue: { (notes) in
self.notes = notes
})
}
}
}//class
数据元素:
struct MyNote: Codable, Identifiable {
let id = UUID()
var title: String
var url: String
var thumbnailUrl: String
static var placeholder: MyNote {
return MyNote(title: "No Title", url: "", thumbnailUrl: "")
}
}
网络设置:
class Webservice {
func fetchNotes() -> AnyPublisher<[MyNote], Error> {
let url = "https://jsonplaceholder.typicode.com/photos"
guard let notesURL = URL(string: url) else { fatalError("The URL is broken")}
return URLSession.shared.dataTaskPublisher(for: notesURL)
.map { $0.data }
.decode(type: [MyNote].self, decoder: JSONDecoder())
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
}
控制台输出为:
任务 . 以错误结束 [-999] 错误域=NSURLErrorDomain 代码=-999 “已取消” UserInfo={NSErrorFailingURLStringKey=https://jsonplaceholder.typicode.com/photos, NSLocalizedDescription=取消, NSErrorFailingURLKey=https://jsonplaceholder.typicode.com/photos}
任何指导将不胜感激。 Xcode 11.4
【问题讨论】:
标签: ios json xcode swiftui combine