如何在IPhone中中止同步的URL请求

时间:2011-03-19 20:52:58

标签: iphone nsurl

我有一个API调用。从服务器获取响应需要2分钟以上。如何在处理时手动中止?

这是我的代码:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setTimeoutInterval: 600.0];
[request setHTTPMethod:@"GET"];

NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];

[headers setValue:@"application/json" forKey:@"Content-Type"];
[headers setValue:@"application/json" forKey:@"Accept"];
[headers setValue:val forKey:@"Authorization"];

[request setAllHTTPHeaderFields:headers];   

NSError *Error;
NSURLResponse *response = [[NSURLResponse alloc] init];

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&Error];

[[NSURLConnection alloc] initWithRequest:request delegate:self];

如何在处理请求时中止请求。

由于

2 个答案:

答案 0 :(得分:0)

你做不到。如果您希望能够取消,请使用异步连接。

另外,BTW,你的代码中有一些错误:

NSError *Error;
NSURLResponse *response = [[NSURLResponse alloc] init];

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&Error];

[[NSURLConnection alloc] initWithRequest:request delegate:self];
  1. 为了更好地衡量,Error应初始化为nil。
  2. 您正在泄漏response。将其初始化为nil,sendSynchronousRequest:returningResponse:error:将填充它(如果请求成功,无论如何)。
  3. [[NSURLConnection alloc] initWithRequest:request delegate:self]启动异步连接并将其释放, 后,您已为同一请求执行了同步连接。它泄漏了NSURLConnection对象。您是否在self对象上实现了非正式委托协议的必要方法?

答案 1 :(得分:0)

您不能,因为同步请求阻止了该线程。

  

同步加载构建在类提供的异步加载代码之上。当异步(sic)加载系统在专门为此加载请求生成的线程上执行URL加载时,调用线程被阻塞。

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html