我正在尝试了解进行 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()
}
}
控制台输出为:
Task <85208F00-BC24-44AA-B644-E0398FE263A6>.<1> finished with error [-999] Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://jsonplaceholder.typicode.com/photos, NSLocalizedDescription=cancelled, NSErrorFailingURLKey=https://jsonplaceholder.typicode.com/photos}
任何指导将不胜感激。 Xcode 11.4
最佳答案
let pub = Webservice().fetchNotes()
该发布者在范围退出时被释放,因此使其成为成员,例如
private var publisher: AnyPublisher<[MyNote], Error>?
func getWebserviceNotes() {
self.publisher = Webservice().fetchNotes()
...
关于ios - SwiftUI 结合 URLSession JSON 网络调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61115014/