用于NSString的Base64编码

Cyr*_*ril 4 iphone base64 nsmutableurlrequest ios

我想将用户名和密码发布到服务器.我想将此用户名和密码转换为Base64编码.因此,将为Authorization字段添加此编码字符串.

是否有任何API可用于在iOS中进行Base64编码,或者我们自己编写?

Rah*_*hul 5

这可以通过实现base64转换的类方法来完成,下面的代码用于转换.

+ (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];
}
Run Code Online (Sandbox Code Playgroud)

并在您的URL请求中添加以下代码以发送授权的用户名和密码...

[请求addValue:[NSString stringWithFormat:@"Basic%@",[className base64forData:[[NSString stringWithFormat:@"%@:%@",UsernameString,passwordString] dataUsingEncoding:NSUTF8StringEncoding]]] forHTTPHeaderField:@"Authorization"] ;