开发者

How to abort a synchronized URL request in IPhone

I have an API call. It takes more than 2 minute to get a response from the server. how can i abort it manually while it is processing?

Here is my code:

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 = [[NSURLRespon开发者_StackOverflow中文版se alloc] init];

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

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

how can i abort the request while its processing.

Thanks


You can't. Use asynchronous connections if you want to be able to cancel.

Also, BTW, you have some errors in your code:

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

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

[[NSURLConnection alloc] initWithRequest:request delegate:self];
  1. For good measure, Error should be initialized to nil.
  2. You are leaking response. Initialize it to nil, and sendSynchronousRequest:returningResponse:error: will fill it in (if the request succeeds, anyway).
  3. The line [[NSURLConnection alloc] initWithRequest:request delegate:self] starts an asynchronous connection and releases it, after you already did a synchronous connection for the same request. And it leaks the NSURLConnection object. Did you even implement the necessary methods for the informal delegate protocol on your self object?


You can't, as the thread is being blocked by your synchronous request.

synchronous load is built on top of the asynchronous loading code made available by the class. The calling thread is blocked while the asynchronous (sic) loading system performs the URL load on a thread spawned specifically for this load request.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜