Search code examples
iosswiftbase64nsdata

How to create base 64 Data in swift


I'm trying to create base64 data for protobuf encoding library. I found this code:

/* Create a Base-64, UTF-8 encoded NSData from the receiver's contents using the given options.
*/
@availability(iOS, introduced=7.0)
func base64EncodedDataWithOptions(options: NSDataBase64EncodingOptions) -> NSData

In the source code of NSData. As I got, this method have to return base64encoded NSDate.

But I can't understand, how to convert my NSData(which I'm receiving from API) to this Base64 NSDate.


Solution

  • You said your data is NSData. Then just call the base64EncodedDataWithOptions and assign it to a new variable/constant:

    let newData = yourData.base64EncodedDataWithOptions(NSDataBase64EncodingOptions.allZeros)
    

    Check NSDataBase64EncodingOptions for encoding options and change allZeros as appropriate.