我正嘗試連接到iOS應用程序中的服務器。這裏是我的代碼:在iOS中連接到服務器didRecieveAuthenticationChallenge時未調用?
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
NSLog(@"This is happening");
NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"user"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int code = [httpResponse statusCode];
NSLog(@"%i",code);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", newStr);
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
NSLog(@"here...");
return YES;
}
,這是在viewDidLoad中:
NSString *url = @"http://example.com:9999/";
NSURL * URL = [NSURL URLWithString:url];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:URL];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection self];
,這是代表們的頭:
<NSURLConnectionDelegate,NSURLConnectionDataDelegate>
didReceiveAuthenticationChallenge不會被調用,但didReceiveResponse是調用並打印「401」,didReceiveData返回頁面上的文本「需要驗證」。
didReceiveAuthenticationChallenge從來沒有被調用,canAuthenticateAgainstProtectionSpace也是如此,所以我無法進行身份驗證。我該如何補救?
是'canAuthenticateAgainstProtectionSpace'叫或不? – Nerkatel
它沒有被調用。 – DCIndieDev