Skip to content

Instantly share code, notes, and snippets.

@mattbischoff
Last active November 20, 2015 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattbischoff/c194015fdd492c62a400 to your computer and use it in GitHub Desktop.
Save mattbischoff/c194015fdd492c62a400 to your computer and use it in GitHub Desktop.
An extension on `NSURL` to support Data URIs. See https://en.wikipedia.org/wiki/Data_URI_scheme
import Foundation
/// An extension on `NSURL` to support Data URIs.
extension NSURL {
/// `true` if the receiver is a Data URI. See https://en.wikipedia.org/wiki/Data_URI_scheme.
var dataURI: Bool {
return scheme == "data"
}
/// Extracts the base 64 data string from the receiver if it is a Data URI. Otherwise or if there is no data, returns `nil`.
var base64EncodedDataString: String? {
guard dataURI else { return nil }
let components = absoluteString.componentsSeparatedByString(";base64,")
return components.last
}
/// Extracts the data from the receiver if it is a Data URI. Otherwise or if there is no data, returns `nil`.
var base64DecodedData: NSData? {
guard let string = base64EncodedDataString else { return nil }
// Ignore whitespace because "Data URIs encoded in Base64 may contain whitespace for human readability."
return NSData(base64EncodedString: string, options: .IgnoreUnknownCharacters)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment