簡體   English   中英

結合使用NSURLCredentialStorage和同步NSURLConnection

[英]Using NSURLCredentialStorage with a synchronous NSURLConnection

我遇到的問題與這里的問題非常相似: 我可以使用NSURLCredentialStorage進行HTTP基本身份驗證嗎?

該問題的作者接受了一個答案,但后來發布了該解決方案代碼返回了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都將使用此憑據

這可能無法完全回答您的問題,但是:通過NSURLConnection進行的同步抓取有很多問題(身份驗證是至少一個問題),並且如果有可能,您應該真正地重組應用程序以使用異步API,這很可能不會您遇到有關身份驗證的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM