求助 Alamofire 的 publisher 用法

2021-12-03 08:44:09 +08:00
 SorryChen

在学习 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 呢,谢谢大家。

1371 次点击
所在节点    Swift
3 条回复
paopaosa
2021-12-03 08:51:45 +08:00
打开外网访问的权限了吗?
SorryChen
2021-12-03 08:54:05 +08:00
@paopaosa 额谢谢,好像没注意这个事情,我去研究研究,纯 mac 开发新手哈哈
SorryChen
2021-12-03 08:58:25 +08:00
@paopaosa 您好,在弄了权限之后发现,使用如下方式可以收到数据:

```
AF.request("https://jsonplaceholder.typicode.com/posts", method: .get, parameters: nil)
.response { r in
print(r.data)
}
```

但是 publisher 还是不行

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/819691

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX