iOS版。如何在Grand Central Dispatch的上下文中处理URL身份验证质询

时间:2012-05-03 20:49:38

标签: ios nsurlconnection grand-central-dispatch nsurlconnectiondelegate

我正在大量使用Grand Central Dispatch。我现在需要发出需要身份验证的服务器的URL请求。 iOS方法NSURLConnection是异步的,这使我使用GCD进行异步任务变得复杂。据我所知NSURLConnection确实支持同步模式,但这需要在请求URL中嵌入user / pass,这是没有意义的,因为我不知道。我有什么选择?

谢谢,
道格

2 个答案:

答案 0 :(得分:0)

不幸的是,您唯一的选择是使用异步请求。使用sendSynchronousRequest:returningResponse:error:方法无法处理身份验证问题。

答案 1 :(得分:0)

实际上,同步请求会在失败之前检查现有凭据的钥匙串。如果存在,它将使用默认凭证。 因此,例如,在您启动网络连接之前,代码中的某处:

NSURLProtectionSpace    *protectionSpace    = nil;
NSURLCredential         *credential         = nil;

// Note that you can't wildcard realm, if your server will present a realm you need that here as well.
protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:@"foo.com" port:80 protocol:@"http" realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic];

// This creates the credential
credential = [NSURLCredential credentialWithUser:user password:pass persistence:NSURLCredentialPersistencePermanent];

// This stores it, in the application keychain.
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace];

现在将其设置为该保护空间的默认凭据,URL加载系统将在访问该保护空间时查找并使用该凭据。简单!这不会做的一件事是基于SSL的身份验证 - NSURLAuthenticationMethodClientCertificate和NSURLAuthenticationMethodServerTrust。由于各种原因,NSURLConnection要求您在此情况下实现委托以评估服务器和客户端的信任。但是,对于您的基本身份验证问题,使用上面的代码进行设置。

但要回答有关GCD和NSURLConnection的更大问题,您可以选择。当然,您可以执行所有博客帖子所说的内容并在异步块内使用同步请求,这可能对您有用(或爆炸)。您还可以使用较新的方法sendAsynchronousRequest:queue:completionHandler:。这将为您解决许多问题,因为委托回调将在提供的队列上运行。它确实使事情变得简单了!

这也值得一读:Five Reasons Synchronous Networking is Bad eskimo1值得一听;)

相关问题