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;
//the completion is only called if the operation wasn't cancelled
- (void) setCompletion:(BITNetworkCompletionBlock) completionBlock;
@property (nonatomic, readonly) NSHTTPURLResponse *response;

View File

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