问题描述
我想在 [NSURLConnection sendAsynchronousRequest: 的答案得到一个好的状态代码时使用 NSMutableURLRequest 发起一个请求.当我单独启动包含 NSMutableURLRequest 的 executeForStatusOkMetod 时,它运行良好.
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.
但如果我使用 [NSURLConnection sendAsynchronousRequest: 启动 executeForStatusOkMetod,则永远不会调用 connectionDidFinishLoading: 函数.
But if I launch the executeForStatusOkMetod with the [NSURLConnection sendAsynchronousRequest:, the connectionDidFinishLoading: function is never called.
主要代码如下:
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];
}
}];
这是调用的函数:
(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];
}
为什么 connectionDidFinishLoading: 没有通过位于 [NSURLConnection sendAsynchronousRequest: 方法中的 NSMutableURLRequest 的调用来调用?
Why connectionDidFinishLoading: is not called with the call of the NSMutableURLRequest located in a [NSURLConnection sendAsynchronousRequest: method ?
推荐答案
在第一个示例中,未调用委托方法,因为 API 不包含用于设置委托的参数.
In the first example the delegate method is not called because the API does not contain a parameter to set the delegate.
在带有完成处理程序的 API 中,当完成处理程序被执行时,连接就完成了.
In the API with completion handler the connection is finished when the completion handler is executed.
这篇关于connectionDidFinishLoading: 未使用 [NSURLConnection sendAsynchronousRequest: queue: completionHandler:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!