NSURLConnection synchronous problem
I am writing an iPhone app which will call a webservice method by using soap message format. I need a synchronous process because table view needs those data before it can be displayed. So I use [NSURLConnection sendSynchronousRequest:returningResponse:error:]
The problem is, the whole program will exit without any error message after the method call. Even I put a NSLog statement just after the [NSURLConnection sendSynchronousRequest:returningResponse:error:], there is no any output so I am sure the program exit during that method call. Actually during that HTTP request and response stuff.
However, if I set a breakpoint before that method call, and run the program in debug mode, everything runs well, the program will not exit, and I got my results as well.
Can anyone figure out what is going on? Thanks.
- (void) sendSyncHTTPRequest:(NSString *)r开发者_运维问答equest_data operation:(ServOperationSync *)serv_ops {
id<ServiceData> serv_data = serv_ops.dataDelegate;
NSURL *urlAddr = [NSURL URLWithString:[serv_data getServURL]];
urlRequest = [NSMutableURLRequest requestWithURL:urlAddr
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:90];
NSData *requestData = [request_data dataUsingEncoding:NSUTF8StringEncoding];
[urlRequest setValue:@"MobilePortal" forHTTPHeaderField:@"User-Agent"];
[urlRequest setValue:[serv_data getSoapAction] forHTTPHeaderField:@"SOAPAction"];
[urlRequest setValue:[NSString stringWithFormat:@"%u", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[urlRequest setValue:urlAddr.host forHTTPHeaderField:@"Host"];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:requestData];
NSLog(@"just before sending http request");
[serv_ops.responseData setData:[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&urlResponse error:&urlError]];
NSLog(@"after sending http request");
}
Note that urlResponse and urlError are declared as instance variables.
You didn't provide us enough code to find out why your app doesn't behave correctly.
Using [NSURLConnection sendSynchronousRequest:returningResponse:error:]
is generally a bad idea, because it blocks the current thread. You are probably calling it from the main thread, this will block the UI. The app won't respond to touches and feels like frozen, when the request takes long (especially on low bandwidth connection like EDGE).
The nature of networking is asynchronous. So I'd advise you to make an asynchronous request instead or use GCD. Update the Tableview in delegate methods (connection:didReceiveData: etc.). You may save the tableview data in an NSMutableArray
and call [tableView reloadData]
after modifying the array. The tableview would then be constructed from that array in the UITableViewDataSource
delegate methods.
You need:
- a run loop on your code
- and don't forget your NSURLConnection delegates
精彩评论