Created
February 23, 2017 19:45
-
-
Save algal/a5d6126cde9708e81cceaf57768b1ce6 to your computer and use it in GitHub Desktop.
Extract the data from certain "data:" URIs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // known-good Xcode 8.2.1 | |
| extension URL | |
| { | |
| /** | |
| Returns the data from a URI with the "data:" scheme, which includes the optional "base64" annotation, and which has a mediatype that is encoded in ASCII. As described in https://tools.ietf.org/html/rfc2397. | |
| */ | |
| var asData:Data? | |
| { | |
| guard | |
| let scheme = self.scheme, scheme == "data", | |
| let path = URLComponents(url: u, resolvingAgainstBaseURL: false)?.path, | |
| let regex = try? NSRegularExpression(pattern: "^.*;base64,", options: []), | |
| let firstMatch = regex.firstMatch(in: path, options: [], range: NSMakeRange(0, path.characters.count)) | |
| else { return nil } | |
| let dataString = path.substring(from: path.index(path.startIndex, offsetBy: firstMatch.range.length)) | |
| guard let data = Data(base64Encoded: dataString) else { return nil } | |
| return data | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment