【问题标题】:Using NSURLCredentialStorage with a synchronous NSURLConnection将 NSURLCredentialStorage 与同步 NSURLConnection 一起使用
【发布时间】:2010-08-02 21:35:36
【问题描述】:

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

该问题的作者接受了答案,但后来发布解决方案代码返回 NSURLErrorUserCancelledAuthentication 错误。我正在使用DIGEST 身份验证,但否则我的代码正在做同样的事情,并返回同样的错误。

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

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

【问题讨论】:

    标签: iphone objective-c cocoa authentication


    【解决方案1】:

    绝对可以。创建你的 NSURLCredential,并添加到 NSURLCredentialStorage 作为保护空间的 default。 示例:

    // 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 都将使用此凭据

    【讨论】:

      【解决方案2】:

      这可能无法完全回答您的问题,但是:通过 NSURLConnection 进行的同步获取有很多问题(身份验证是最少的问题),如果可能的话,您应该真正重组您的应用程序以改用异步 API,这很可能不会出现您看到的有关身份验证的问题。

      【讨论】:

      • 哦,真的吗?我们在这里谈论什么样的问题?我确实需要该应用程序等待连接返回...
      • 我最终只是这样做了——我稍微重组了我的应用程序以使用异步 API。这不是我理想的解决方案,但它确实有效。 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多