connectionDidFinishLoading: not called with the use of [NSURLConnection sendAsynchronousRequest: queue: completionHandler:

大城市里の小女人 提交于 2019-12-12 05:12:03

问题


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

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