[英]value: (failure(Alamofire.AFError.explicitlyCancelled)) when use Alamofire publisher
I;m learning SwiftUI and Alamofire.我正在学习 SwiftUI 和 Alamofire。 I created a demo APP like this:
我创建了一个这样的演示APP:
import SwiftUI
import Alamofire
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.padding()
.onAppear(perform: load)
}
struct TestResponse: Decodable {
let userId: Int
let id: Int
let title: String
let body: String
}
func load(){
AF.request("https://jsonplaceholder.typicode.com/posts", method: .get, parameters: nil)
.validate()
.publishDecodable(type: [TestResponse].self)
.print()
.sink { print($0) }
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
But I got this output:但我得到了这个 output:
receive subscription: (Alamofire.DataResponsePublisher<Swift.Array<Test.ContentView.TestResponse>>.(unknown context at $1080f8314).Inner<Combine.Publishers.Print<Alamofire.DataResponsePublisher<Swift.Array<Test.ContentView.TestResponse>>>.(unknown context at $7ff81332d748).Inner<Combine.Subscribers.Sink<Alamofire.DataResponse<Swift.Array<Test.ContentView.TestResponse>, Alamofire.AFError>, Swift.Never>>>)
request unlimited
receive cancel
receive value: (failure(Alamofire.AFError.explicitlyCancelled))
receive finished
if I use the .response
to receive the data, everything is ok.如果我使用
.response
接收数据,一切正常。
Thanks for any help.谢谢你的帮助。
You need to store the token returned by sink
(which you're likely getting a compiler warning about).您需要存储
sink
返回的令牌(您可能会收到编译器警告)。 Otherwise the publisher you created is immediately cancelled and the underlying request is cancelled as well.否则,您创建的发布者将立即取消,并且基础请求也将被取消。 You can use a
Set<AnyCancellable>
to and sink {}.store(in: &set)
, or find an alternate solution.您可以使用
Set<AnyCancellable>
来接收sink {}.store(in: &set)
,或者找到替代解决方案。 For SwiftUI you'll likely want to put your networking in some sort of model object, not the view.对于 SwiftUI,您可能希望将您的网络置于某种 model object 中,而不是视图中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.