André Fratelli
André Fratelli

Reputation: 6068

Encoding/decoding arbitrary binary data to string in swift/objective-c

I need to encode/decode an arbitrary NSData object into a String/NSString. Here's what I have for encoding:

    var avatar64 = self.avatar.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!);
    let avatarData = NSData(base64EncodedString: avatar64, options: NSDataBase64DecodingOptions.fromRaw(0)!);
    let avatar = NSString(data: avatarData, encoding: NSUTF8StringEncoding);

But avatar is nil. What am I doing wrong?

Upvotes: 1

Views: 6281

Answers (1)

Martin R
Martin R

Reputation: 539815

Your first step already creates a Base64-encoded string of the data in self.avatar:

var avatar64 = self.avatar.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!);

Your second step decodes the Base64 string again, so that avatarData contains the same binary data as your original self.avatar:

let avatarData = NSData(base64EncodedString: avatar64, options: NSDataBase64DecodingOptions.fromRaw(0)!);

Finally, your third step tries to create a string from the original (binary) data:

let avatar = NSString(data: avatarData, encoding: NSUTF8StringEncoding);

This fails because the data is not a valid UTF-8 sequence.

In short: Just remove the third and second line.

Upvotes: 3

Related Questions