我一直回到同樣的問題。對于我的應用程式的其他部分,我在決議 API 后直接使用了 coredata,效果很好。但是,現在我想決議通過 API 接收到的 JSON 并獲取一個值,用于計算其他值,然后將其放入 Coredata。
一切正常,我設定了 URLSessions 代碼如下:
func fetchData(brand: String, completion: @escaping ((Double) -> Void)) {
let urlString = "\(quoteUrl)\(brand)"
if let url = URL(string: urlString) {
var session = URLRequest(url: url)
session.addValue("application/json", forHTTPHeaderField: "Accept")
session.addValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: session) { (data, response, error) in
if error != nil {
print(error!)
return
}
if let safeData = data {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(DataModel.self, from: safeData)
let bid = decodedData.quotes.quote.bid
let ask = decodedData.quotes.quote.ask
let itemPrice: Double = (bid ask)/2
completion(itemPrice)
} catch {
print(error)
}
}
}
task.resume()
}
}
我正在使用 completionHandler 來檢索我需要在另一個檔案中使用的部分,如下所示:
func getGainLossNumber(brand: String, quantity: Int, price: Double) -> Double {
var finalPrice = 0.0
APImodel.fetchData(brand: brand) { returnedDouble in
let currentPrice = returnedDouble
if quantity < 0 {
let orderQuantity = quantity * -1
finalPrice = price (currentPrice*(Double(orderQuantity))*100)
} else {
finalPrice = price - (currentPrice*(Double(quantity))*100)
}
}
return finalPrice
}
finalPrice 最終回傳 0.0。如果我在閉包中列印 currentPrice ,我會得到正確的結果。由于我面臨的問題,我使用完成處理程式從 API 中檢索一個數字,但它仍然沒有做我想要的。第二個函式應該回傳使用我從 API 中獲得的值計算出的值,該 API 是我使用完成處理程式檢索到的。
我只是不知道該怎么做。
uj5u.com熱心網友回復:
問題是您正在finalPrice一個閉包內進行計算,它是異步的。但是,您的 getGainLossNumber 方法是同步的,因此它實際上在您的閉包計算完成之前回傳finalPrice。重構您的代碼,以便getGainLossNumber將閉包作為引數,并finalPrice在計算完成后呼叫它。就像是:
func getGainLossNumber(brand: String, quantity: Int, price: Double, _ completion: @escaping (Double) -> Void) {
APImodel.fetchData(brand: brand) { returnedDouble in
let currentPrice = returnedDouble
let finalPrice: Double
if quantity < 0 {
let orderQuantity = quantity * -1
finalPrice = price (currentPrice*(Double(orderQuantity))*100)
}
else {
finalPrice = price - (currentPrice*(Double(quantity))*100)
}
completion(finalPrice)
}
}
另請注意,finalPrice 不需要是var,因為它只會被賦值一次。
編輯
用法:
getGainLossNumber(brand: "brand", quantity: 1, price: 120, { finalPrice in
// You can access/use finalPrice in here.
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361701.html
