【发布时间】:2021-02-24 11:27:20
【问题描述】:
我正在尝试使用此帮助文件获取一些数据: https://gist.github.com/jbfbell/e011c5e4c3869584723d79927b7c4b68
这是重要代码的sn-p:
类
/// Base class for requests to the Alpha Vantage Stock Data API. Intended to be subclasssed, but can
/// be used directly if library does not support a new api.
class AlphaVantageRequest : ApiRequest {
private static let alphaApi = AlphaVantageRestApi()
let method = "GET"
let path = ""
let queryStringParameters : Array<URLQueryItem>
let api : RestApi = AlphaVantageRequest.alphaApi
var responseJSON : [String : Any]? {
didSet {
if let results = responseJSON {
print(results)
}
}
}
}
扩展 ApiRequest
/// Makes asynchronous call to fetch response from server, stores response on self
///
/// - Returns: self to allow for chained method calls
public func callApi() -> ApiRequest {
guard let apiRequest = createRequest() else {
print("No Request to make")
return self
}
let session = URLSession(configuration: URLSessionConfiguration.ephemeral)
let dataTask = session.dataTask(with: apiRequest) {(data, response, error) in
guard error == nil else {
print("Error Reaching API, \(String(describing: apiRequest.url))")
return
}
self.receiveResponse(data)
}
dataTask.resume()
return self
}
我的目标是在加载 url 请求的数据后从 responseJSON 中获取数据。
我的 ViewModel 目前看起来像这样:
class CompanyViewModel: ObservableObject {
var companyOverviewRequest: ApiRequest? {
didSet {
if let response = companyOverviewRequest?.responseJSON {
print(response)
}
}
}
private var searchEndpoint: SearchEndpoint
init(companyOverviewRequest: AlphaVantageRequest? = nil,
searchEndpoint: SearchEndpoint) {
self.companyOverviewRequest = CompanyOverviewRequest(symbol: searchEndpoint.symbol)
}
func fetchCompanyOverview() {
guard let request = self.companyOverviewRequest?.callApi() else { return }
self.companyOverviewRequest = request
}
}
所以在我的 ViewModel 中,didSet 被调用一次,但不是在它应该存储数据的时候。 AlphaVantageRequest 的结果总是能正确打印出来,但不是在我的 ViewModel 中。我怎样才能在我的 ViewModel 中也有加载的数据?
【问题讨论】:
-
我强烈建议使用您自己的“API”层来使用 Combine,它只是 URLSession 的一个薄包装器。你会发现很多例子在 5 行代码中实现了获取、解码和错误处理。无需使用这种复杂的 API 层,它也有几个严重的缺陷。
-
一个更好的问题标题是“视图如何使用视图模型和网络 API 获取数据,同时添加标签“组合”。
标签: api swiftui protocols viewmodel combine