Skip to content

Instantly share code, notes, and snippets.

@hlxwell
Created August 7, 2020 04:20
Show Gist options
  • Save hlxwell/54f6760d1167858a9fc1f91ba4a26341 to your computer and use it in GitHub Desktop.
Save hlxwell/54f6760d1167858a9fc1f91ba4a26341 to your computer and use it in GitHub Desktop.
extension String {
func base64Encoded() -> Data? {
return self.data(using: .utf8)
}
func base64Decoded() -> Data? {
if self.range(of: ":")?.lowerBound != nil {
return self.data(using: .utf8)
}
let base64String = self.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
let padding = base64String.count + (base64String.count % 4 != 0 ? (4 - base64String.count % 4) : 0)
return Data(base64Encoded: base64String.padding(toLength: padding, withPad: "=", startingAt: 0), options: NSData.Base64DecodingOptions(rawValue: 0))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment