【问题标题】:How to cancel an asynchronous HTTP request in Objective-C?如何在 Objective-C 中取消异步 HTTP 请求?
【发布时间】:2014-07-17 02:22:54
【问题描述】:

我正在尝试添加在用户离开视图或发起新请求时取消所有当前异步请求的功能。我知道将代码放在哪里,但我不太确定如何实际取消请求。根据我的研究,我知道NSURLConnection 有一个cancel 方法,但我使用异步块调用我的请求。以下是我的代码 - 非常感谢任何帮助!

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:[kEndpointEvents stringByAppendingString:arguments]]];

//Send an asynchronous request so it doesn't pause the main thread
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

    NSHTTPURLResponse *responseCode = (NSHTTPURLResponse *)response;

    //Do stuff

}];

【问题讨论】:

    标签: ios objective-c networking asynchronous


    【解决方案1】:

    使用便捷方法+sendAsynchronousRequest:queue:completionHandler+sendSynchronousRequest:returningResponse:error: 时,无法取消正在进行的请求。

    如果您想取消,请实现委托NSURLConnectionDataDelegate 中的方法,并通过回调自己构建数据。这样做将使您能够控制连接对象,并且您可以随时在其上调用-cancel

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多