NSURLConnection delegate methods are not called

≯℡__Kan透↙ 提交于 2019-11-26 19:17:29

问题


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?


回答1:


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];



回答2:


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:


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




回答4:


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.



来源:https://stackoverflow.com/questions/5787170/nsurlconnection-delegate-methods-are-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!