ios – 使用NSURLConnection进行身份验证sendAsynchronousRequest与完成处理程序

前端之家收集整理的这篇文章主要介绍了ios – 使用NSURLConnection进行身份验证sendAsynchronousRequest与完成处理程序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
通常我喜欢使用NSURL的sendAsynchronousRequest类方法,使用完成处理程序块来“点燃和忘记”,但似乎在需要验证时可能不是一个选项.

当使用完成处理程序样式请求,如下所示:

[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.mysite.com/"]]
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,NSData *data,NSError *error) {


                            //Do Stuff   

                           }];

处理身份验证的正确方法是什么?我需要分配和初始化NSURLConnection并设置代理,而不是使用此类方法样式?我想我知道如何使用委托函数正确地进行身份验证,但是我想知道我是否可以将它包含在completionHandler块中,或者是否有更好的方法来执行此操作.

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{

    if ([challenge prevIoUsFailureCount] > 0) {
        NSLog(@"Authentication Failure");
        [connection cancel];
    }
    else
    {

        NSURLCredential *credential = [NSURLCredential credentialWithUser:self.username
                                                                 password:self.password
                                                              persistence:NSURLCredentialPersistenceForSession];
        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
    }

}

解决方法

我认为completionHandler方法是基本请求.也许你可以考虑使用 AFNetworking,因为我使用块方法和身份验证.

编辑….
您是否尝试将身份验证标头添加到NSURLRequest?
创建一个NSMutableURLRequest:

NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.mysite.com/"]];

添加如下认证头:

NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@",userName,password];
NSString *authValue = [NSString stringWithFormat:@"Basic %@",AFBase64EncodedStringFromString(basicAuthCredentials)];
[urlRequest setValue:authValue forHTTPHeaderField:@"Authorization"];

AFBase64EncodedStringFromString函数是这样的:

static NSString * AFBase64EncodedStringFromString(NSString *string) {
    NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
    NSUInteger length = [data length];
    NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];

    uint8_t *input = (uint8_t *)[data bytes];
    uint8_t *output = (uint8_t *)[mutableData mutableBytes];

    for (NSUInteger i = 0; i < length; i += 3) {
        NSUInteger value = 0;
        for (NSUInteger j = i; j < (i + 3); j++) {
            value <<= 8;
            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }

        static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

        NSUInteger idx = (i / 3) * 4;
        output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
        output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
        output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6)  & 0x3F] : '=';
        output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0)  & 0x3F] : '=';
    }

    return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}

然后调用您之前调用函数,但使用您的新NSURLRequest:

[NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,NSError *error) {


                            //Do Stuff   

                           }];

猜你在找的iOS相关文章