0

iOS アプリでサーバーに接続しようとしています。これが私のコードです:

- (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 も呼び出されないため、認証できません。これを解決するにはどうすればよいですか?

4

2 に答える 2