值:(失败(Alamofire.AFError.explicitlyCancelled))当使用 Alamofire 发布者时

value: (failure(Alamofire.AFError.explicitlyCancelled)) when use Alamofire publisher

我正在学习 SwiftUI 和 Alamofire。我创建了一个这样的演示应用程序:


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([=11=]) }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

但我得到了这个输出:

receive subscription: (Alamofire.DataResponsePublisher<Swift.Array<Test.ContentView.TestResponse>>.(unknown context at 80f8314).Inner<Combine.Publishers.Print<Alamofire.DataResponsePublisher<Swift.Array<Test.ContentView.TestResponse>>>.(unknown context at ff81332d748).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接收数据,一切正常

感谢您的帮助。

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