ios - 快速解码 httpsCallable 云函数响应

标签 ios swift firebase google-cloud-functions swift5

我有一个从应用程序调用的 httpsCallable 云函数。从技术上讲,它工作正常,但如您所见,代码嵌套非常多,我觉得可以以某种方式更好地处理它。我也会收到警告。

响应 result?.data 是类型 Any 所以我不能在 中直接使用它试试 decoder.decode(PaymentIntent.self, from: data ) 因为这需要 Data 类型。为此,我正在使用 try? JSONSerialization.data(withJSONObject: result?.data)

知道如何将所有内容解码为 PaymentIntent 模型吗?

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

functions.httpsCallable("createPaymentIntent").call(data) { (result, error) in
    if let error = error as NSError? {
        completion(nil, error)
    } else {
        let data = try? JSONSerialization.data(withJSONObject: result?.data)
        
        if let data = data {
            do {
                let paymentIntent = try decoder.decode(PaymentIntent.self, from: data) // Expression implicitly coerced from 'Any?' to 'Any'
                completion(paymentIntent.clientSecret, nil)
            } catch {
                completion(nil, error);
            }
        }

        // Update

        if let data = result?.data as? NSDictionary {
            print(data)
            
            do {
                // Cannot convert value of type 'NSDictionary' to expected argument type 'Data'
                let paymentIntent = try decoder.decode(PaymentIntent.self, from: data)
                completion(paymentIntent.clientSecret, nil)
            } catch {
                completion(nil, error);
            }
        }
    
    }
}

最佳答案

Swift SDK for Firebase 的可调用函数不返回 JSON 字符串。它返回已从 JSON 反序列化的数据类型。它要么是字典、数组,要么是直接对应于云函数生成的任何内容。您应该进行一些逐步调试以检查 result.data 实际是什么,然后 write some code to verify that it is what you expect , 并转换它以便安全地使用它。

关于ios - 快速解码 httpsCallable 云函数响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66645888/

相关文章:

ios - 在静态 TableView 中添加和设置 TableViewCell

swift - 我无法弄清楚这个 switch 语句是如何工作的?

ios - xcode gm ios 8 gm swift 今天扩展在模拟器和设备中崩溃 : Library not loaded: @rpath/libswiftCore. dylib

javascript - 如何更改新 Firebase onUpdate 或 onWrite 触发器中的值?

Android App Crawler 不工作 -> 权限拒绝失败

ios - 设置UIlabel的高度

ios - 在标题内的 MKAnnotationView 中添加图片

iphone - Snow Leopard 上的 iOS SDK 4.3 安装错误

arrays - 将字典中的范围附加到 Swift 中的数组

ios - 什么 'type' 是 removeObserverWithHandle 的 Firebase 句柄应该在 Swift 中?