我正在學習 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($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接收資料,則一切正常。
謝謝你的幫助。
uj5u.com熱心網友回復:
您需要存盤由sink(您可能會收到編譯器警告)回傳的令牌。否則,您創建的發布者將立即被取消,并且基礎請求也將被取消。您可以使用Set<AnyCancellable>to 和sink {}.store(in: &set),或找到替代解決方案。對于 SwiftUI,您可能希望將網路置于某種模型物件中,而不是視圖中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/373398.html
上一篇:更改表單標簽的顏色
