从另一个文件中快速调用完成处理程序失败

时间:2018-12-29 06:08:33

标签: swift completionhandler

我正在使用带有completio = n处理函数的函数从一个调用转移到另一个类

叫课:

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)
            }

        } catch {
            print("error: \(error.localizedDescription)")

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

呼叫班:

 func estimate() {
  var estimatedSolarkWh:Double = 0.0
 let aPVClass = PVClass()
aPVClass.estimateMonthlyACkW(areaSqFt: 100.0,  completion: { (monthlyAckW) -> Void in

           estimatedSolarkWh = monthlyAckW
            self.view.setNeedsDisplay()
       })
return 
}
}

当我调用函数estimate()时,另一个PVClass中的estimateMonthlyACkW函数已执行,但在执行调用estimate()函数后返回。因此,即使在被调用的函数中执行了URLsession,也解析了json,并且正确打印了值-该值永远不会转移到完成处理程序中,并且该值永远不会回到调用类中。我该如何解决?

1 个答案:

答案 0 :(得分:0)

您需要在打印语句之后移动completion(self.avgMonthlyAcKw),如下所示:

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

希望这会对您有所帮助:)

相关问题