【发布时间】:2021-06-14 20:23:11
【问题描述】:
我有一个 POST 请求,向用户发送一条短信,该短信不返回任何内容,只返回状态码。我尝试返回 AnyPublisher
这是我的通用请求方法的样子:
func request<T>(_ req: NetworkRequest) -> AnyPublisher<T, NetworkError> where T: Decodable, T: Encodable {
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = TimeInterval(req.requestTimeout ?? requestTimeout)
guard let url = URL(string: req.url) else {
// Return a fail publisher if the url is invalid
return AnyPublisher(
Fail<T, NetworkError>(error: NetworkError.badURL("Invalid Url"))
)
}
// We use the dataTaskPublisher from the URLSession which gives us a publisher to play around with.
return URLSession.shared
.dataTaskPublisher(for: req.buildURLRequest(with: url))
.tryMap { output in
// throw an error if response is nil
guard output.response is HTTPURLResponse else {
throw NetworkError.serverError(code: 0, error: "Server error")
}
return output.data
}
.decode(type: T.self, decoder: JSONDecoder())
.mapError { error in
// return error if json decoding fails
NetworkError.invalidJSON(String(describing: error))
}
.eraseToAnyPublisher()
}
【问题讨论】:
-
“它不起作用”是什么意思?另外,所有这些中的发布请求在哪里?数据任务不会执行发布请求。
-
twilioService .generateCode(to: formattedPhoneNo) .sink(receiveCompletion: { (completion) in switch completion { case .failure(let error): print("ERROR: (error.localizedDescription)") 案例.finished: return } }, receiveValue: { (res) in print("RESPONSE: (res)") }) .store(in: &cancellables) }
-
Xcode 没有指责 post 请求调用有任何错误,错误出在 post 所附图片中提供的实现方法上。
-
好吧,不要附上图片。请不要有代码图片。如果需要代码来描述问题,请将其发布为代码(文本)。
标签: ios swift http swiftui combine