0

I have a query. I wanted to perform some operation asynchronously, say downloading a big file from internet inside UIViewController. I wrote a Method in delegate which takes request and block as parameter

-(void)downloadDataFromURL:(NSMutableURLRequest *)_request withCompletionHandler:(void (^)(NSData *, bool ))completionHandler{

[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *_response, NSData *_data, NSError *_error)
 {
     completionHandler(_data, true);

 }];

}

In my viewDidLoad method looks like this

- (void)viewDidLoad{
mainDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

[mainDelegate downloadDataFromURL:[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@""]] withCompletionHandler:^(NSData *_data, bool isFinished)
 {
     //Processed only if we are inside memory. anyway there are many leaks when I load these class again
}];

[super viewDidLoad];
// Do any additional setup after loading the view.}

now there is back button which pop the view controller

- (IBAction)BackBtnClicked:(id)sender{
[self.navigationController popViewControllerAnimated:true];}

So how can I detect if I have popped the controller from memory inside my completionHandler? Or how can I cancel the completionHandler from getting executed. Because if I don't there will be leaks.

  • basically you want to cancel the `sendAsynchronousRequest` call? – Ravi B Jul 15 '16 at 13:46
  • its just example.. I am implementing a Class where I will just a pass Url and completion block for callBack which will execute when that task complete – Nelson Pereira Jul 15 '16 at 14:06
  • Ok that fine, so basically you can use NSOperation and find last object from that queue and cancel the request. Like this. `NSOperation *lastOp = [self.downloadQ.operations lastObject]; [lastOp cancel];` – Ravi B Jul 15 '16 at 14:08
  • check my edited question – Nelson Pereira Jul 15 '16 at 14:23
  • inside your completionHandler you can use : to check if your VC is stil in the view: dispatch_async(dispatch_get_main_queue(), ^{ if (weakSelf.view.window) { [weakSelf.tableView reloadData]; } }]; – Idali Jul 15 '16 at 14:33
  • is these correct way to create weakSelf? __weak typeof(self) weakSelf = self; – Nelson Pereira Jul 18 '16 at 06:19

0 Answers0