首页 > 解决方案 > DispatchQueue.main.async 块中未更新完成处理程序的返回值

问题描述

我正在从一个类调用一个带有完成处理程序的函数到另一个类

称为类:

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,值永远不会转移到当前类范围,UI 更新失败,即使在 DispatchQueue.main.async 之后如何解决这个问题?

标签: swiftcompletionhandlerdispatch-queue

解决方案


的电话completion是在错误的地方。将其移到打印行之后的数据任务的完成闭包中

    // prints value
    print("updated estimate: ", self.avgMonthlyAcKw)
    completion(self.avgMonthlyAcKw)

并在恢复后将其删除

dataTask.resume()
completion(self.avgMonthlyAcKw)
}


推荐阅读