问题
I would like to launch a request with NSMutableURLRequest when the answer of the [NSURLConnection sendAsynchronousRequest: get a good status code. When I launch the executeForStatusOkMetod containing the NSMutableURLRequest alone, it works perfectly.
But if I launch the executeForStatusOkMetod with the [NSURLConnection sendAsynchronousRequest:, the connectionDidFinishLoading: function is never called.
Here is the main code :
NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
request.timeoutInterval = 10;
[NSURLConnection sendAsynchronousRequest:request queue:myQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"response status code: %ld, error status : %@", (long)[httpResponse statusCode], error.description);
if ((long)[httpResponse statusCode] >= 200 && (long)[httpResponse statusCode]< 400)
{
// do stuff
[[DataManagement sharedManager] executeForStatusOkMetod];
}
}];
Here is the function called :
(void) executeForStatusOkMetod
{
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSString *url_string = [bytes stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
[request setURL:[NSURL URLWithString:[set_send_order stringByAppendingString: url_string]]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:timeOut];
[NSURLConnection connectionWithRequest:request delegate:self];
}
Why connectionDidFinishLoading: is not called with the call of the NSMutableURLRequest located in a [NSURLConnection sendAsynchronousRequest: method ?
回答1:
In the first example the delegate method is not called because the API does not contain a parameter to set the delegate.
In the API with completion handler the connection is finished when the completion handler is executed.
来源:https://stackoverflow.com/questions/42490047/connectiondidfinishloading-not-called-with-the-use-of-nsurlconnection-sendasyn