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,这是完整的代码。所以,这可能就是问题所在