iphone - 将 NSURLCredentialStorage 与同步 NSURLConnection 结合使用

标签 iphone objective-c cocoa authentication

我遇到的问题与这里的问题非常相似:Can I use NSURLCredentialStorage for HTTP Basic Authentication?

该问题的作者接受了答案,但后来发布说解决方案代码返回 NSURLErrorUserCancelledAuthentication 错误。我正在使用 DIGEST 身份验证,但除此之外我的代码正在执行相同的操作,并返回相同的错误。

我不想以明文形式发送用户名和密码,因此我绝对不想简单地将用户名和密码添加到 URL 的前面。有没有办法让 NSURLConnection 的 sendSynchronousRequest:returningResponse:error: 方法查阅共享的 NSURLCredentialStorage?这听起来像是类别适合做的事情,但我完全不知道如何做到这一点——听起来我必须完全重新实现 sendSynchronousRequest:returningResponse:error: 方法让它工作。

如何执行查询共享 NSURLCredentialStorage 的同步 URL 连接?

最佳答案

绝对可以。创建您的 NSURLCredential,并将其添加到 NSURLCredentialStorage 作为保护空间的默认。 示例:

// Permananent, session, whatever.
NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence: NSURLCredentialPersistencePermanent];
// Make sure that if the server you are accessing presents a realm, you set it here.
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:@"blah.com" port:0 protocol:@"http" realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
// Store it
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace];

此时,使用与您设置的保护空间相匹配的保护空间进行质询的任何后续 NSURLConnection 都将使用此凭据

关于iphone - 将 NSURLCredentialStorage 与同步 NSURLConnection 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3391976/

相关文章:

cocoa - Mac 上单实例应用程序的理想方式

objective-c - Objective-C 中的 const 与静态 NSStrings

iphone - 使用半透明条形样式时,导航栏不设置动画

iPhone 3DES加密 key 长度问题

iphone - 数据库安装路径无效。 - 钛合金加速器

objective-c - 释放错误 [NSPersistentStoreCoordinator initWithManagedObjectModel]

python - NSPipe - 如何将返回的数据转换为 NSArray

ios - CollectionView 编程滚动

objective-c - 导出符号文件 : Objective C derived class members, 64 位

ios - iOS 中的 Paypal 定期付款