首页 > 解决方案 > 无法使用 Combine 执行 urlSession 请求

问题描述

无法Data使用Combine,控制台上没有打印任何内容。

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 { $0.data }
            .decode(type: [Repository].self, decoder: JSONDecoder())
            .sink(receiveCompletion: { completion in // 5
                print(completion)
            }, receiveValue: { repositories in
                print("brunosilva808 has \(repositories.count) repositories")
            })
    }
}

标签: swiftcombine

解决方案


它不起作用,因为您的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 { $0.data }
            .decode(type: [Repository].self, decoder: JSONDecoder())
            .sink(receiveCompletion: { completion in // 5
                print(completion)
            }, receiveValue: { repositories in
                print("brunosilva808 has \(repositories.count) repositories")
            })

    }
}

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


推荐阅读