值:(failure(Alamofire.AFError.explicitlyCancelled)) 使用 Alamofire 发布者时

Posted

技术标签:

【中文标题】值:(failure(Alamofire.AFError.explicitlyCancelled)) 使用 Alamofire 发布者时【英文标题】:value: (failure(Alamofire.AFError.explicitlyCancelled)) when use Alamofire publisher 【发布时间】:2022-01-09 11:19:21 【问题描述】:

我正在学习 SwiftUI 和 Alamofire。我创建了一个这样的演示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()
    

但我得到了这个输出:

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

如果我使用.response接收数据,一切正常。

感谢您的帮助。

【问题讨论】:

【参考方案1】:

您需要存储sink 返回的令牌(您可能会收到编译器警告)。否则,您创建的发布者将立即取消,并且基础请求也将被取消。您可以使用Set&lt;AnyCancellable&gt;sink .store(in: &amp;set),或找到替代解决方案。对于 SwiftUI,您可能希望将网络放在某种模型对象中,而不是视图中。

【讨论】:

以上是关于值:(failure(Alamofire.AFError.explicitlyCancelled)) 使用 Alamofire 发布者时的主要内容,如果未能解决你的问题,请参考以下文章

软件测试之 Failure, Error & Fault

软件测试[2]falut error failure 的区别与理解

软件测试作业2:fault,error,failure 的区别

解决mysql连接报“Communications link failure”错误

junit 方法:assertEquals 和 assertTrue

org.apache.spark.SparkException:job aborted due to stage failure spark driver maxResultSize (1024)