在学习 macOS 开发想捣鼓个小东西自己用,零基础。这两天研究了研究 Publisher ,感觉也算是大概懂了,但是在用 Alamofire 的 publisher 的时候,怎么也搞不定了。比如如下这个只有一个函数的 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
为什么会出现 explicitlyCancelled 呢,谢谢大家。
1
paopaosa 2021-12-03 08:51:45 +08:00
打开外网访问的权限了吗?
|
3
SorryChen OP @paopaosa 您好,在弄了权限之后发现,使用如下方式可以收到数据:
``` AF.request("https://jsonplaceholder.typicode.com/posts", method: .get, parameters: nil) .response { r in print(r.data) } ``` 但是 publisher 还是不行 |