我正在从一个类到另一个类调用带有完成处理程序的函数
称为班级:
class PVClass
{
var avgMonthlyAcKw:Double = 0.0
var jsonString:String!
func estimateMonthlyACkW (areaSqFt:Float, completion: @escaping(Double) -> () ){
var capacityStr:String = ""
let estimatedCapacity = Float(areaSqFt/66.0)
capacityStr = String(format: "%.2f", estimatedCapacity)
// Build some Url string
var urlString:String = "https://developer.nrel.gov/"
urlString.append("&system_capacity=")
urlString.append(capacityStr)
let pvURL = URL(string: urlString)
let dataTask = URLSession.shared.dataTask(with: pvURL!) { data, response, error in
do {
let _ = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
self.jsonString = String(data: data!, encoding: .utf8)!
print("JSON String:\(String(describing: self.jsonString))")
if self.jsonString != nil {
let decoder = JSONDecoder()
let jsonData = try decoder.decode(PVClass.Top.self, from: data!)
// do some parsing here
var totalAcKw: Double = 0.0
let cnt2: Int = (jsonData.Outputs?.ACMonthly.count)!
for i in 0..<(cnt2-1) {
totalAcKw = totalAcKw + (jsonData.Outputs?.ACMonthly[i])!
}
self.avgMonthlyAcKw = Double(totalAcKw)/Double(cnt2)
// prints value
print("updated estimate: ", self.avgMonthlyAcKw)
completion(self.avgMonthlyAcKw)
}
} catch {
print("error: \(error.localizedDescription)")
}
}
dataTask.resume()
}
通话类:
aPVClass.estimateMonthlyACkW(areaSqFt: 100.0, completion: { (monthlyAckW) -> Void in
DispatchQueue.main.async { [weak self] in
guard case self = self else {
return
}
print("monthlyAckW: ", monthlyAckW)
self?.estimatedSolarkWh = Int(monthlyAckW * Double((12)/365 * (self?.numDays)!))
print("estimatedSolarkWh: ", self?.estimatedSolarkWh ?? 0)
guard let val = self?.estimatedSolarkWh else { return }
print("val: ", val)
self?.estimatedSolarkWhLabel.text = String(val)
self?.view.setNeedsDisplay()
}
})
}
完成处理程序返回后,monthlyAckW具有正确的值。但是为self?.estimatedSolarkWh分配的值是0,即使从DispatchQueue.main.async之后,该值也永远不会传输到当前类范围,UI更新失败 请问该如何解决?
答案 0 :(得分:0)
completion
的呼叫在错误的位置。在打印行之后将其移至数据任务的完成结束处
// prints value
print("updated estimate: ", self.avgMonthlyAcKw)
completion(self.avgMonthlyAcKw)
并在恢复后将其删除
dataTask.resume()
completion(self.avgMonthlyAcKw)
}