From 2909fd0ac0d9fdb2cdb7fd25e38742451aa05fb1 Mon Sep 17 00:00:00 2001 From: jcesarmobile Date: Thu, 27 Aug 2020 18:02:33 +0200 Subject: [PATCH] feat: Add extension for creating data from data url (#3474) --- ios/Capacitor/Capacitor/Data+Capacitor.swift | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 ios/Capacitor/Capacitor/Data+Capacitor.swift diff --git a/ios/Capacitor/Capacitor/Data+Capacitor.swift b/ios/Capacitor/Capacitor/Data+Capacitor.swift new file mode 100644 index 000000000..1105c581a --- /dev/null +++ b/ios/Capacitor/Capacitor/Data+Capacitor.swift @@ -0,0 +1,22 @@ +extension Data: CapacitorExtension {} +public extension CapacitorExtensionTypeWrapper where T == Data { + + static func data(base64EncodedOrDataUrl: String) -> Data? { + if isBase64DataUrl(base64EncodedOrDataUrl) { + if let url = URL(string: base64EncodedOrDataUrl) { + do { + return try T(contentsOf: url) + } catch { + return nil + } + } + return nil + } else { + return T(base64Encoded: base64EncodedOrDataUrl) + } + } + + private static func isBase64DataUrl(_ base64EncodedOrDataUrl: String) -> Bool { + return base64EncodedOrDataUrl.starts(with: "data:") && base64EncodedOrDataUrl.contains("base64,") + } +}