Search code examples
ioscore-datansurlsessionnsurlsessiondatatask

NSURLSessionDataTask cancel and Core Data


I've got NSURLSession, that downloads new user profiles from server, then for each profile downloads array of photos, and than stores in Core Data. Every time the user reaches this screen i stop downloading tasks, clear Core Data, than fill it again. The problem is, that cancel() function is async, so it manages to save some profiles AFTER i cleared Core Data. Moreover, these profiles can be without some data thanks to datatask cancel. So, the question is as follows - how to correctly finish download tasks and after that clear core data? Thanks in advance.


Solution

  • I would recommend using NSOperation class for what you need.

    https://developer.apple.com/library/ios/documentation/Cocoa/Reference/NSOperation_class/

    You should wrap-up operation for downloading data into NSOperation class and before you add results to CoreData you can check if NSOperation was cancelled in between.

    @interface DownloadOperation: NSOperation
    @end
    
    @implementation DownloadOperation
    - (void)main {
        @autoreleasepool {
            [Server downloadDataFromServer:^(id results) {
                 if (self.isCancelled == NO)
                 {
                    [CoreData saveResults:results];
                 }
            }];
        }
    }
    @end
    

    You add your operation to NSOperationQueue:

    NSOperationQueue *queue= [[NSOperationQueue alloc] init];
    [queue addOperation:[[DownloadOperation alloc] init]];
    

    And you can cancel it by calling:

    [operation cancel];
    

    or canceling all operations:

    [queue cancelAllOperations];