的NSURLConnection的該-asBase64EncodedString
方法會工作得很好。正如在另一個答案中指出的那樣,執行回調函數很容易。
- (void) someMethod
{
NSURLRequest* request = [[NSURLRequest alloc]
initWithURL:[NSURL urlWithString:@"someURL"]
NSURLConnection* connection = [[NSURLConnection alloc]
initWithRequest:request delegate:self];
[connection release];
[request release];
}
這是非常簡單的。它在NSURLConnection的所有魔術發生的代表方法中:
這是處理憑證挑戰的地方。我已經硬編碼了一個假的用戶名和密碼來演示它的工作原理。我個人有一個單獨的委託對象處理挑戰。請記住,連接將處於空閒狀態,直到您響應或連接超時。
- (void) connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
// Make sure to use the appropriate authentication method for the server to
// which you are connecting.
if ([[challenge protectionSpace] authenticationMethod] ==
NSURLAuthenticationMethodBasicAuth)
{
// This is very, very important to check. Depending on how your
// security policies are setup, you could lock your user out of his
// or her account by trying to use the wrong credentials too many
// times in a row.
if ([challenge previousFailureCount] > 0)
{
[[challenge sender] cancelAuthenticationChallenge:challenge];
UIAlertView* alert = [[UIAlertView alloc]
initWithTitle:@"Invalid Credentials"
message:@"The credentials are invalid."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
[challenge useCredential:[NSURLCredential
credentialWithUser:@"someUser"
password:@"somePassword"
persistence:NSURLCredentialPersistenceForSession
forAuthenticationChallenge:challenge]];
}
}
else
{
// Do whatever you want here, for educational purposes,
// I'm just going to cancel the challenge
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
你需要實現一個NSURLConnection的這些方法,以及:
// So you know when it's done downloading
- (void) connectionDidFinishLoading:(NSURLConnection *)connection;
// In case of failure
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
// Gather the downloaded file data
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
感謝您的幫助。我使用了大部分示例代碼,但遇到了一些問題。首先是NSURLAuthenticationMethodBasicAuth無法識別,我剛剛評論說剛剛出來。另一個是forAuthenticationChallenge:挑戰]] ;.括號出來了,但沒有辦法,我會得到這麼遠沒有你的幫助,所以再次感謝。 – paulnug 2011-03-12 15:09:58