add cancellation support

This commit is contained in:
Stephan Diederich 2013-08-15 22:59:08 +02:00
parent 4f6f871bf3
commit d80e8090a7
2 changed files with 15 additions and 7 deletions

View File

@ -17,6 +17,7 @@ typedef void (^BITNetworkCompletionBlock)(BITHTTPOperation* operation, id respon
@property (nonatomic, readonly) NSURLRequest *URLRequest; @property (nonatomic, readonly) NSURLRequest *URLRequest;
//the completion is only called if the operation wasn't cancelled
- (void) setCompletion:(BITNetworkCompletionBlock) completionBlock; - (void) setCompletion:(BITNetworkCompletionBlock) completionBlock;
@property (nonatomic, readonly) NSHTTPURLResponse *response; @property (nonatomic, readonly) NSHTTPURLResponse *response;

View File

@ -38,22 +38,27 @@
} }
- (void) start { - (void) start {
if(self.isCancelled) {
[self finish];
return;
}
if (![[NSThread currentThread] isMainThread]) { if (![[NSThread currentThread] isMainThread]) {
[self performSelector:@selector(start) onThread:NSThread.mainThread withObject:nil waitUntilDone:NO]; [self performSelector:@selector(start) onThread:NSThread.mainThread withObject:nil waitUntilDone:NO];
} }
if(self.isCancelled) {
[self finish];
return;
}
[self willChangeValueForKey:@"isExecuting"]; [self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES; _isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"]; [self didChangeValueForKey:@"isExecuting"];
_connection = [[NSURLConnection alloc] initWithRequest:_URLRequest _connection = [[NSURLConnection alloc] initWithRequest:_URLRequest
delegate:self delegate:self
startImmediately:NO]; startImmediately:YES];
[_connection scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[_connection start];
} }
- (void) finish { - (void) finish {
@ -101,7 +106,9 @@
typeof(self) strongSelf = weakSelf; typeof(self) strongSelf = weakSelf;
if(strongSelf) { if(strongSelf) {
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
completion(strongSelf, strongSelf->_data, strongSelf->_error); if(!strongSelf.isCancelled) {
completion(strongSelf, strongSelf->_data, strongSelf->_error);
}
[strongSelf setCompletionBlock:nil]; [strongSelf setCompletionBlock:nil];
}); });
} }