相关疑难解决方法(0)

使用完成处理程序通过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   

                           }];
Run Code Online (Sandbox Code Playgroud)

处理身份验证的正确方法是什么?我是否需要分配和初始化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];
    }

}
Run Code Online (Sandbox Code Playgroud)

authentication nsurlconnection ios

12
推荐指数
2
解决办法
2万
查看次数

标签 统计

authentication ×1

ios ×1

nsurlconnection ×1