ios - SwiftUI 结合 URLSession JSON 网络调用

标签 ios json xcode swiftui combine

我正在尝试了解进行 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/

相关文章:

PHP json_encode 将数字索引创建为字符串而不是对象

objective-c - XCode 4.5 警告父/子类类别之间的方法名称冲突

IOS/objective-C : Load one record from Core Data without loading table first

ios - 随机和数字图像不相同 iOS xCode

android - 如何使用改造将 json 数据发送到服务器?

java - 玩2.3.x框架: How to decline all non application/json requests

c++ - 使用 XCTest 编写 C++ 单元测试

ios - 将项目升级到 Xcode 8

iOS 和 RESTful 网络服务加密

javascript - 找不到 Phonegap.js