I am getting a crash when dismissing a view controller while making an async GET request. What I have tried to do is end all operations in viewWillDissapear, but I am still getting the crash. Any ideas what the fix to this is?
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[AFHTTPRequestOperationManager manager].operationQueue cancelAllOperations];
}
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSMutableArray *responseArray = [responseObject mutableCopy];
NSMutableIndexSet *indexesToDelete = [NSMutableIndexSet indexSet];
NSUInteger currentIndex = 0;
for (NSDictionary *track in responseArray) {
if ([track objectForKey:@"streamable"] == [NSNumber numberWithBool:false]) {
[indexesToDelete addIndex:currentIndex];
}
currentIndex++;
}
[responseArray removeObjectsAtIndexes:indexesToDelete];
completion((NSArray *) responseArray, (BOOL) NO);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
completion((NSArray *) nil, (BOOL) YES);
[[NSNotificationCenter defaultCenter]postNotificationName:@"networkError" object:nil];
}];
A good practice to avoid this kind of crash is to separate the Data from the View controllers. Basically you would have data manager that will hold the data, this will be a singleton that will live for the entire app session. A view controller would read data from this data manager, if not available would make a Http request via DataMgr, and the response will be received by DataMgr. Once the response is received a notification will be sent by the DataMgr to update the UI of the view controller is still available.
This pattern helps you get away from crashes and also organize all your data in one place. And also refused the round trips to the server saving the battery on the device as well.
In your code I notice that you are canceling all the requests and that's is not recommended. What you should be doing there is stop to all notification listeners instead, and register for listeners when view will load instead.
For now if you can share sole more of your code and crash may new I can tell exactly what's going wrong. Use Blocks with __weak , google more in this to get more info.