Last active
November 20, 2015 20:16
-
-
Save mbbischoff/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
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
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