简体   繁体   中英

How to encode and decode NSString in iOS?

I am developing an app which should support iOS5,iOS6,iOS7.

In my app i want to encode my NSString Data using base64encoding .

Following is the code I am using for encoding

NSString *userData = @"data";
NSString *base64EncodedString = [[userData dataUsingEncoding:NSUTF8StringEncoding] 
base64EncodedStringWithOptions:0];

The above code is running fine in iOS7, but in iOS6 the application crashes,with the following error:

[NSConcreteMutableData base64EncodedStringWithOptions:]

Is there any other way to encode data Or any function which support iOS6 & iOS7.

Can anyone help me out with this?

Thanks in Advance

Can't comment for some reason, so I'll link to an old StackOverflow answer that provides a plausible solution. Basically, you convert the NSString to NSData and encode the NSData.

+ (NSString *)toBase64String:(NSString *)string {
    NSData *data = [string dataUsingEncoding: NSUnicodeStringEncoding];
    NSString *ret = [NSStringUtil base64StringFromData:data length:[data length]];
    return ret;
}

Of course, you could check for iOS7 and use initWithBase64EncodedString:options: for that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM