I have a httpsCallable cloud function which is being called from the app. Technically speaking it is working fine but as you can see, the code is very nested and I have the feeling that this can be handled somehow better. I also get a warning.
The response result?.data
is of type Any
so I can not use it directly in try decoder.decode(PaymentIntent.self, from: data)
since this requires Data
type. And for this I'm using try? JSONSerialization.data(withJSONObject: result?.data)
Any idea how to decode everything to PaymentIntent
model?
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);
}
}
}
}