Skip to content

Instantly share code, notes, and snippets.

@edc0der
Created October 20, 2017 20:21
Show Gist options
  • Save edc0der/ee77ebd1aa54e87a79c820af2edc8300 to your computer and use it in GitHub Desktop.
Save edc0der/ee77ebd1aa54e87a79c820af2edc8300 to your computer and use it in GitHub Desktop.
Encode and decode base64 from String
extension String {
var base64encoded: String? {
if let data = self.data(using: .utf8) {
return data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
}
return nil
}
var base64decoded: String? {
if let data = Data(base64Encoded: self) {
return String.init(data: data, encoding: .utf8)
}
return nil
}
}
@edc0der
Copy link
Author

edc0der commented Oct 20, 2017

I'm sure somebody else has already shared a similar (if not the same) way to do this, but it's what I did in a project I'm working on where I needed to encode in base64 without a new line feed or carriage return.

The code was originally in Objective-C, and had a problem where the person who did the encoding, as there's not a Base64EncodingOption of the type none or something of the like, they used the option:

return data.base64EncodedString(options: .lineLength64Characters)

The problem was that this included a '\n\r' to the encoded text when the encoded length was above 64 characters, which our server didn't know how to interpret.

So, taking the opportunity to do a little refactoring, I created this extension in the project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment