Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 无法使用Combine执行urlSession请求_Swift_Combine - Fatal编程技术网

Swift 无法使用Combine执行urlSession请求

Swift 无法使用Combine执行urlSession请求,swift,combine,Swift,Combine,无法使用组合获取数据,控制台上没有打印任何内容 struct RepositoryElement: Codable {} class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let url = URL(string: "https://api.github.com/users/brunosilva

无法使用
组合
获取
数据
,控制台上没有打印任何内容

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")
            })
    }
}

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

如果你这样做的话,它应该会起作用。您需要导入联合收割机,因为
anycancelable
是联合收割机的一部分

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")
            })

    }
}

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

您将可取消的存储在哪里?@Andrew,这是完整的代码。所以,这可能就是问题所在