1

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

That's what I had to begin with... I ended up adding to it because it was failing somewhere else. I guess I was wrong to do it. I'll file another question. Thank you.
Hi, I have stucked in same kind of situation. I make creating a UIImage like , var image: UIImage = UIImage(named:"one12.png"). Then I am converting the image to NSData like,var data1:NSData = UIImagePNGRepresentation(image), Now I am converting the NSData back to String like, let base64String = data1.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!) as String. Now I am paasing the image as parameter to the server like, var params = ["username":"json", "password":"iosi","profile_img":base64String]as NSDictionary . What I am doing wrong? Please explain me.
@Annu How did you solve this. I'm also stuck with the similar issue. Sometime image is passed properly and sometime it does not.
@Ankita Sorry, but I still haven't implemented this. Actually I was trying to implement this one in a demo project. I'll post the answer when I'll implement.
@Annu, Thanks for your reply. My issue is solved now. Before request was as URLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type"), then I added URLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") URLRequest.setValue("application/json", forHTTPHeaderField: "Accept"). As we are passing json data so we can directly set content type like this rather then using form encoding
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.