NSURLConnection delegate methods are not called

2019-01-13 05:03发布

I am trying to create a simple NSURLConnection to communicate with a server using a GET request. Connection works well, but delegates methods of NSURLConnection are never called..

Here is what am doing:

NSString *post = [NSString stringWithFormat:@"key1=%@&key2=%@&key3=%f&key4=%@", val1, val4, val3, val4];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease] ;

[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.domain.com/demo/name/file.php?%@", post]]];

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

Have implemented the following delegate methods, but none of them is called..

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"did fail");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"did receive data");
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"did receive response ");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"did finish loading");
    [connection release];
}

Am I missing something?

4条回答
Emotional °昔
2楼-- · 2019-01-13 05:57

Are you calling this on a background thread? If you are performing this on a background thread, the thread is probably exiting before the delegates can be called.

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-13 05:58

Apart from checking if the request is called from the main thread, you can check if you give back execution time to the system (if you exit "main"). I had some test code that would stay in a loop until the delegate was called : it would never be called, because the system needs to do stuff in order for the delegate to be called, in the main thread.

查看更多
戒情不戒烟
4楼-- · 2019-01-13 06:03

Try running the operation on main thread:

NSURLConnection * connection = [[NSURLConnection alloc] 
                                initWithRequest:request
                                       delegate:self startImmediately:NO];

[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] 
                      forMode:NSDefaultRunLoopMode];
[connection start];
查看更多
唯我独甜
5楼-- · 2019-01-13 06:03

Try to check length for the received response it should not getting 0 byte of data.

查看更多
登录 后发表回答