3

I am sending a request to server using NSURLConnection, it worked for 2 times , since third time it is not working, delegates are not being called. What i found during debugging is connectionShouldUseCredentialStorage method is called for initial times, third time it was not called and rest of methods are also not called.

Here is my code:

    NSString *requestString = [NSString stringWithFormat:@"%@", [serviceParameters JSONFragment], nil];

    NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: strUrl]];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
    [request setHTTPBody:requestData];
    [NSURLConnection connectionWithRequest:urlRequest delegate:self];


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.data = [NSMutableData data];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData
{
    [self.data appendData:aData];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    SBJSON *jsonParser = [[SBJSON new] autorelease];
    NSString *jsonString = [[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding] autorelease];
    NSError *outError = nil;

    id result = [jsonParser objectWithString:jsonString error:&outError];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}


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


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

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
    return YES;
}
Soumya Ranjan
  • 4,817
  • 2
  • 26
  • 51
SwathiK
  • 364
  • 3
  • 13
  • did you try putting breakpoints in NSURL delegate methods? also can you try increasing timeout. – user2071152 May 15 '14 at 06:48
  • Can you check whether the returned NSURLConnection is not nil, if([NSURLConnection connectionWithRequest:urlRequest delegate:self] != nil) { NSLog(@"connectgion started"); } – Satheesh May 15 '14 at 06:51
  • 3
    are you running it from the main thread or, if not the main thread, from a thread connected to a run loop? Based on documentation: "Delegate methods are called on the same thread that called this method. For the connection to work correctly, the calling thread’s run loop must be operating in the default run loop mode. " – viggio24 May 15 '14 at 06:51
  • @user2071152 I tried using breakpoints and tried with time out 300 value, but didn't help to fix the issue. – SwathiK May 15 '14 at 06:52
  • @satheeshwaran: I tried your code, it is showing connection started. NSURLConnection is not nil. – SwathiK May 15 '14 at 06:54
  • @viggio24 currently i am calling that method by using self, now i change to run that method by using performSelectorOnMainThread it worked.What is the reason? – SwathiK May 15 '14 at 07:00
  • Probably the calling method was not in the main thread. You can check this by adding this code, just before the NSURLConnection setup: if([NSThread currentThread]==[NSThread mainThread]) {NSLog("This is the main thread");} else {NSLog(@"Not main thread!");} Probably your method is the output of some block that run in a secondary thread. – viggio24 May 15 '14 at 09:58

2 Answers2

0

in .h

NSMutableData * data;
NSURLConnection *connection;

Also add Add

in .m

-(void) startConnection
{
    NSString *requestString = [NSString stringWithFormat:@"http://md5.jsontest.com/?text=Pushkraj"];

    NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:60.0];


    data = [NSMutableData dataWithCapacity:0];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
    [request setHTTPBody:requestData];
    connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    data = [NSMutableData data];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData
{
    [data appendData:aData];
    NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    NSLog(@"dataDict : %@",dataDict);
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connectionDidFinishLoading");
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Error : %@",error);
}

Call [self startConnection]; wherever you want means on viewDidLoad or on UIButton Click

Pushkraj Lanjekar
  • 2,254
  • 1
  • 21
  • 34
0

You forgot to start connection. You are not saving the reference to NSURLConnection for starting the connection. So replace last line

[NSURLConnection connectionWithRequest:urlRequest delegate:self];

with this

NSURLConnection *cn =[NSURLConnection connectionWithRequest:urlRequest delegate:self];
[cn start];

Hope it helps.

NaXir
  • 2,373
  • 2
  • 24
  • 31