Методы делегата NSURLConnection вызываться не будут ... не могу разобраться и прочитать много постов - PullRequest
4 голосов
/ 23 ноября 2010

У меня есть класс с именем BackendConnector, который использует NSURLConnection для вызова SoapWebservice, то есть https. Я нашел много постов и попытался реализовать методы делегатов, касающиеся аутентификации, но они не были вызваны, и через 6 часов в Google я не понял, что сделал неправильно. Может кто-нибудь дать мне подсказку, почему эти 2 метода делегата не будут вызваны? Я установил точку останова в каждой из них, запустил свое приложение с XCode в симуляторе, но все равно получаю ошибку, и точки останова не попадают.

BackendConnector.m

#import "BackendConnector.h"

@implementation BackendConnector

@synthesize dataPoint, chartDataPoints;

- (NSMutableArray *)GetWebserviceData
{
    NSMutableData *myMutableData;
    chartDataPoints = [[NSMutableArray alloc] init];

    [self createWebserviceAndGetResponse: &myMutableData];

    if (myMutableData != NULL)
    {
        NSString *theXml = [[NSString alloc]initWithBytes:[myMutableData mutableBytes] length:[myMutableData length] encoding:NSUTF8StringEncoding];

        NSLog(@"doc = %@", theXml);

        arrayCount = 0;
        [self parseResponse: myMutableData];
    }
    else 
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
                                                        message:@"There is no Data returned from Webservice!"
                                                       delegate:nil 
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles: nil];
        [alert show];
        [alert release];
}

    return NULL;
    //return chartDataPoints;
}

- (void) createWebserviceAndGetResponse: (NSMutableData **) myMutableData_p  
{
    NSMutableString *sRequest = [[NSMutableString alloc]init];

    [sRequest appendString:@"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.ReportWebservice.xyz.com/\">"];
    [sRequest appendString:@"<soapenv:Header/>"];
    [sRequest appendString:@"<soapenv:Body>"];
    [sRequest appendString:@"<ser:getReport>"];
    [sRequest appendString:@"<arg0>User/arg0>"];
    [sRequest appendString:@"<arg1>password</arg1>"];
    [sRequest appendString:@"</ser:getReport>"];
    [sRequest appendString:@"</soapenv:Body>"];
    [sRequest appendString:@"</soapenv:Envelope>"];

    NSURL *myWebserverURL = [NSURL URLWithString:@"https://xyz.com/services/report"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myWebserverURL]; 
    NSLog(@"request: %@", request);

    [request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"" forHTTPHeaderField:@"SOAPAction"];

    NSString *contentLengthStr = [NSString stringWithFormat:@"%d", [sRequest length]];

    [request addValue:contentLengthStr forHTTPHeaderField:@"Content-Length"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[sRequest dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if(conn)
    {
        *myMutableData_p=[[NSMutableData data] retain];
    }

    [NSURLConnection connectionWithRequest:request delegate:self];

    NSError *WSerror;
    NSURLResponse *WSresponse;

    *myMutableData_p = [NSURLConnection sendSynchronousRequest:request returningResponse:&WSresponse error:&WSerror];
}

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
@end

Ошибка:

Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “xyz.com” which could put your confidential information at risk." UserInfo=0x8161600 {NSErrorFailingURLStringKey=https://xyz.com/services/report, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSErrorFailingURLKey=https://xyz.com/services/report, NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “xyz.com” which could put your confidential information at risk., NSUnderlyingError=0x8134cb0 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “xyz.com” which could put your confidential information at risk.", NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x6d86020>}

Большое спасибо

twickl

Ответы [ 2 ]

6 голосов
/ 18 мая 2011

Поздно, но может быть полезно другим

Ссылка на решение http://www.wim.me/nsurlconnection-in-its-own-thread/

5 голосов
/ 24 ноября 2010

Я не смогу ответить, почему эти методы не запускаются, у меня точно такие же методы, и они вызываются при использовании HTTPS, но мне интересно, почему вы не реализуете остальную часть NSURLConnection делегировать методы?Например, -didReceiveResponse и т. Д.

Я также думаю, что ваше соединение фактически начинается с

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

У вас не должно быть [NSURLConnection connectionWithRequest:request delegate:self];, и, наконец, вы запускаете и устанавливаете другой синхронный NSURLConnection исохраняя его в том, что должно быть NSMutableData.

Попробуйте использовать только свой первый NSUrlConnection *conn (и обязательно верните его правильно позже), а затем настройте свои данные в методе делегата -didReceiveResponse, и вы можетефактически установить или добавить данные в методе делегата -didReceiveData.

...