Base64 Encoding for NSString

I am trying to publish the username and password on the server. I want to convert this username and password to Base64 Encoding. Thus, this encoded string will be added for the authorization field.

Is there any API that is already available for encoding Base64 in iOS, or do we have an entry in our own language?

+4
source share
2 answers

How to make base64 encoding on iphone-sdk?

Look at this.

and then use these methods to use the above methods (listed in the link) Converting NSString to Databases64 for XML serialization is taken from the above link.

+ (NSString *)toBase64String:(NSString *)string { NSData *data = [string dataUsingEncoding: NSUnicodeStringEncoding]; NSString *ret = [NSStringUtil base64StringFromData:data length:[data length]]; return ret; } + (NSString *)fromBase64String:(NSString *)string { NSData *base64Data = [NSStringUtil base64DataFromString:string]; NSString* decryptedStr = [[NSString alloc] initWithData:base64Data encoding:NSUnicodeStringEncoding]; return [decryptedStr autorelease]; } 
+2
source

This can be done by implementing the base64 conversion class method, which is given below for conversion.

 + (NSString*)base64forData:(NSData*)theData { const uint8_t* input = (const uint8_t*)[theData bytes]; NSInteger length = [theData length]; static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; uint8_t* output = (uint8_t*)data.mutableBytes; NSInteger i; for (i=0; i < length; i += 3) { NSInteger value = 0; NSInteger j; for (j = i; j < (i + 3); j++) { value <<= 8; if (j < length) { value |= (0xFF & input[j]); } } NSInteger theIndex = (i / 3) * 4; output[theIndex + 0] = table[(value >> 18) & 0x3F]; output[theIndex + 1] = table[(value >> 12) & 0x3F]; output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '='; output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '='; } return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease]; } 

and in your request url add the following code to send username and password for authorization ...

[request addValue: [NSString stringWithFormat: @ "Basic% @", [className base64forData: [[NSString stringWithFormat: @ "% @:% @", UsernameString, passwordString] dataUsingEncoding: NSUTF8StringEncoding]]] forHTTPHeField] ;

+5
source

Source: https://habr.com/ru/post/1444258/


All Articles