问题
I am having a problem in NSURLConnection. My didRecieveData method is not being called . I dont know what's the problem. I also went through almost all the previous problems but nothing seems to solve.
Please help me out. This is my code.
-(void)gettheJSONdata
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_serverAddress cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[request setHTTPMethod: @"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
NSLog(@"This is displayed");
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data
{
NSLog(@"This is not displayed.");
AppAppDelegate *JSONdata = (AppAppDelegate*)[[UIApplication sharedApplication] delegate];
JSONdata.userloginJSONdata = [[NSData alloc] initWithData:data];
NSError *error;
_result = [NSJSONSerialization JSONObjectWithData:JSONdata.userloginJSONdata options:NSJSONReadingMutableContainers error: &error];
NSString *test = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Json data : %@",test);
}
-(void) connectionDidFinishLoading:(NSURLConnection*) connection
{
AppAppDelegate *resultofJSONdata = (AppAppDelegate*)[[UIApplication sharedApplication] delegate];
resultofJSONdata.JSONdataresult = _result;
}
回答1:
You didn't start the request. You need:
[connection start];
or
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
Edit: My comment below had the incorrect method name. Try implementing both:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
and
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
And see if either of those are being hit.
回答2:
Finally I solved the problem. I didnt synthesize the JSONdataresult.
I didn't realise that this could cause a problem with NSURLConnection.
回答3:
in my case header was No connection didReceiveData not getting called ,be sure to add authorisation if it is required for request,
[urlRequest setValue:[UserContext sharedInstance].requesthandler.reqHeader forHTTPHeaderField:@"Authorization"];
来源:https://stackoverflow.com/questions/10937215/connection-didreceivedata-is-not-called