0

我正嘗試連接到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也是如此,所以我無法進行身份驗證。我該如何補救?

+0

是'canAuthenticateAgainstProtectionSpace'叫或不? – Nerkatel

+0

它沒有被調用。 – DCIndieDev

回答

0

您必須在您的url中使用https而不是http來調用此方法。

NSString *url = @"https://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]; 
+0

我應該用什麼來代替? – DCIndieDev

+0

剛剛更新了我的答案。你應該使用https://而不是http:// –

+0

啊,我明白了。不幸的是,我連接的網站沒有https設置,只有HTTP。有沒有其他方式連接到普通的http? – DCIndieDev

0

我認爲你缺少一個代表

NSURLAuthenticationChallengeSender