无法使用 Combine 执行 urlSession 请求

Unable to do a urlSession request with Combine

无法使用 Combine 获取 Data,控制台上未打印任何内容。

struct RepositoryElement: Codable {}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = URL(string: "https://api.github.com/users/brunosilva808/repos")!

        let repos = URLSession.shared.dataTaskPublisher(for: url)
            .map { [=10=].data }
            .decode(type: [Repository].self, decoder: JSONDecoder())
            .sink(receiveCompletion: { completion in // 5
                print(completion)
            }, receiveValue: { repositories in
                print("brunosilva808 has \(repositories.count) repositories")
            })
    }
}

它不起作用,因为您的 repo 变量超出范围,因此您的网络请求被取消。您需要保留您的请求,因此在您的 ViewController 中创建一个变量来保留它。

如果你这样做,那么它应该会起作用。您需要导入 Combine,因为 AnyCancellable 是 Combine 的一部分。

import Combine

class ViewController: UIViewController {

    var cancellable: AnyCancellable?

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "https://api.github.com/users/brunosilva808/repos")!

        cancellable = URLSession.shared.dataTaskPublisher(for: url)
            .map { [=10=].data }
            .decode(type: [Repository].self, decoder: JSONDecoder())
            .sink(receiveCompletion: { completion in // 5
                print(completion)
            }, receiveValue: { repositories in
                print("brunosilva808 has \(repositories.count) repositories")
            })

    }
}

我无法检查它是否正确解码,因为你没有包含 Repository 结构。