swift - 无法使用 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")
})
}
}
解决方案
它不起作用,因为您的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 结构。
推荐阅读
- haskell - 找不到模块“Test.Hspec.Discover”
- javascript - 如何从 Swift 调用 jquery 函数?
- c# - 如何设置使用 Database First 生成的 DbContext 的执行策略?
- postgresql - PostgreSQL 中的 Edge NGram 搜索
- c - 普通变量可以保存另一个变量的地址吗?
- php - 使用循环 PHP 5.6 时出现中断、继续和退出问题
- python - 不能多次写入文件。接收 Errno 13 权限被拒绝
- python - 有没有办法按顺序列出所有斐波那契数?
- javascript - 从 amazon-lambda 发送帖子请求时出现问题
- sql-server - 在 SQL Server 中对数据进行子集化后查找行数