URLParameter在数据实时获取期间每秒都会添加到端点,并且端点变得太大



我使用的是一个动态url,每次添加新的currencyAir时都会发生变化。然而,每当触发下面的apiTimer并且url端点每1秒增加一次时,它就会添加一个新的对。但是,它应该仅在向MainTableViewController添加新货币对时才添加,而不是每隔一秒添加一次。

以下是我迄今为止尝试的内容:

  • 将func request((上的endpoint:String更改为endpoint:URLParameters
  • 更改了函数的参数
  • 重新构造了计时器功能

知道问题出在哪里以及如何解决吗?

提前感谢

import Foundation
class NetworkEngine {
/// Executes the web call and will decode the JSON response into Codable object provided
/// - Parameters:
///   - endpoint: the endpoint to make the HTTP request against
///   - completion: the JSON response converted to the provided Codable object, if successful, or failure otherwise
static let shared = NetworkEngine()
func request<T: Codable>(_ endpoint: String, completion: @escaping (Result<T, Error>) -> ()) {
guard let url = URL(string: endpoint) else {
return
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "GET"
print(urlRequest, "respponse2")

let session = URLSession(configuration: .default)
let dataTask = session.dataTask(with: urlRequest) { (data, response, error) in
guard error == nil else {
completion(.failure(error!))
print(error?.localizedDescription ?? "Unknown error")
return
}
guard response != nil, let safeData = data else { return }

DispatchQueue.main.async {
if let responseObject = try? JSONDecoder().decode(T.self, from: safeData) {
completion(.success(responseObject))
} else {
let error = NSError(domain: "", code: 200, userInfo: [NSLocalizedDescriptionKey : "Failed to decode response"])
completion(.failure(error))
print(error)
}
}

}
dataTask.resume()
}
}  
lazy var apiTimer: Timer = {
var timer = Timer()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(urlFetch), userInfo: nil, repeats: true)
return timer
}()
@objc fileprivate func urlFetch() {
guard let endpoint = currencyPairModel.getUrlComponent().url?.absoluteString else { return }
NetworkEngine.shared.request(endpoint) { [weak self] (result: Result<[String: Double], Error>) in
switch result {
case .success(let rateResults):
DispatchQueue.main.async {
print("TESTTTTT")
let cells = self?.currencyListTableView.visibleCells as! [CurrencyListTableViewCell]
for cell in cells {
print(cell,"cell")
print(cells,"cells")
for key in rateResults.keys {
if key == cell.currencyPair.currencyPairKey {
print(key,"key")
cell.currencyPair.addRate(rateResults)
print(rateResults,"rateResults")
print(rateResults.keys,"rateResults.keys")
self?.currencyListTableView.beginUpdates()
cell.rate = cell.currencyPair?.getRate()
self?.currencyListTableView.endUpdates()
}
}
}
}
case .failure(let error):
self?.showAlert(with: "Error!", message: error.localizedDescription)
}
}
}
mutating func getUrlComponent() -> URLComponents {
for currencyPair in currencyPairs {
let param = URLQueryItem(name: "pairs", value: currencyPair.currencyPairKey)
components.queryItems?.append(param)
}
return components
}

好的。您每秒调用getUrlComponent()方法。在这种方法中,您将获得现有的组件,附加成对的查询项,并将组件保存在实例变量中。这就是为什么你的url每秒都在增长。只需清除方法开头的查询项数组。

mutating func getUrlComponent() -> URLComponents {
components.queryItems = []
for currencyPair in currencyPairs {
let param = URLQueryItem(name: "pairs", value: currencyPair.currencyPairKey)
components.queryItems?.append(param)
}
return components
}

您有几个名称相同的查询项pairs,可以吗?

最新更新