Reputation: 33
i'm using afnetworking 2.0 to show youtube videos. When i have a connection error, i open an alert view and i'd like stop the request if i click "ok".
Alert view is showed correctly but when i click "ok" the request isn't stopped and i see activity indicator.
How can i stop the request?
This is the code below:
-(void)loadData {
NSString *urlAsString = @"https://gdata.youtube.com/feeds/api/videos?q=wankel&v=2&max-results=50&alt=jsonc";
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] init];
activityIndicator.color = [UIColor blackColor];
activityIndicator.backgroundColor = [UIColor blackColor];
[activityIndicator startAnimating];
[self.view addSubview:activityIndicator];
activityIndicator.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2 );
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
self.moviesArray = [responseObject valueForKeyPath:@"data.items"];
NSLog(@"%@", moviesArray);
self.thumbnailsArray = [responseObject valueForKeyPath:@"data.items.thumbnail"];
self.moviesDetailArray = [responseObject valueForKeyPath:@"data.items"];
[activityIndicator setHidden:YES];
[activityIndicator stopAnimating];
[self.collectionView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
UIAlertView *alertView =[[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"%@", error.localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Try again", nil];
[activityIndicator setHidden:YES];
[activityIndicator stopAnimating];
[alertView show];
}];
[operation start];
}
Upvotes: 0
Views: 334
Reputation: 1016
Have you tried adding the operation to a AFHTTPRequestOperationManager ? The manager has an operationQueue property. You can cancel operations from there.
When the operation fails, stop the operation from the shared manager.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.operationQueue cancelAllOperations];
Edit: If you're looking for a specific operation you can iterate through the operations in the queue:
for (NSOperation *operation in manager.operationQueue.operations) {
// check if this is the right operation, and cancel it.
}
Upvotes: 1