Skip to content

Instantly share code, notes, and snippets.

@algal
Created February 23, 2017 19:45
Show Gist options
  • Select an option

  • Save algal/a5d6126cde9708e81cceaf57768b1ce6 to your computer and use it in GitHub Desktop.

Select an option

Save algal/a5d6126cde9708e81cceaf57768b1ce6 to your computer and use it in GitHub Desktop.
Extract the data from certain "data:" URIs
// 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