如何在完成处理程序中传递数据

时间:2019-02-06 09:47:41

标签: ios swift closures completionhandler

我正在尝试将IAP收据传递给包含用户的completion handler,并想通过在其他subscription中调用它来检查用户class当前是否处于活动状态我越来越。我该如何解决。

  
    

不能调用非功能类型'((学生)->虚空)的值吗?'

  
func validateReceipt(pReceiptData: Data? = nil, completion pCompletion: ((Student) -> Void)? = nil) {
    let receiptData = pReceiptData!.base64EncodedString()
    let receiptDict: [String: Any] = ["receipt-data": receiptData]
    do {
        let data = try JSONSerialization.data(withJSONObject: receiptDict)
        guard let validationUrl = URL(string: "https://us-central1-myApp-a8e27.cloudfunctions.net/receiptValidation") else { return }
        let session = URLSession(configuration: .default)
        var request = URLRequest(url: validationUrl, cachePolicy: .reloadIgnoringLocalCacheData)
        request.httpMethod = "POST"
        request.httpBody = data
        let task = session.uploadTask(with:request, from: data) { (data, response, error) in
            guard let data = data, error == nil else { return }
            do {
                let receipt = try IAPReceipt.decode(data: data)
                pCompletion(receipt)

            } catch let error {
                print(error.localizedDescription)
            }
        }
        task.resume()
    } catch let error {
        print(error)
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用typealias使函数声明更简洁。看看完成块是如何制作的。

typealias Completion = ((_ student: Student) -> Void)?
func validateReceipt(pReceiptData: Data? = nil, completion: Completion = nil) {
      ...  
}