iosobjective-cnsurlsessionnsurlsessiontasknsurlsessionuploadtask

Checking which kind of NSURLSessionTask occurred


I seem to be running into trouble. For some reason, If I try to check the class type of my NSURLSessionTask objects, it doesn't work at all. If I check their taskDescription properties, this works of course if I set them before initiating the task. I would just like to know why the below code doesn't work for me. I appreciate any help offered!

- (void)uploadIt
{
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    defaultConfigObject.timeoutIntervalForResource = 15.0;
    defaultConfigObject.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;

    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSURLSessionUploadTask *uploadTask = [defaultSession uploadTaskWithRequest:someRequest fromData:body];
    [uploadTask resume];
}  

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    if (self.uploadResponseData)
    {
        NSDictionary *d = [NSJSONSerialization JSONObjectWithData:self.uploadResponseData options:kNilOptions error:nil];
        NSLog(@"Dict: %@",d);
    }

    if ([task isKindOfClass:[NSURLSessionDownloadTask class]])
    {
        // Not called
    }
    else if ([task isKindOfClass:[NSURLSessionUploadTask class]])
    {
        // Not called
    }
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    if (!self.uploadResponseData)
    {
        self.uploadResponseData = [NSMutableData dataWithData:data];
    }
    else
    {
        [self.uploadResponseData appendData:data];
    }
}

Solution

  • My experience with this has been in the context of app-in-the-background NSURLSessionTasks. These get serialized to disk, there's a deamon involved, and my experience is that any class-based finagling didn't work too well in that context.

    Particularly, I was trying to subclass NSURLSessionTask, but what came back in the -didComplete:... call was not an instance of that subclass.

    I've come to think of NSURLSessionTask as a facade, or part of a "class cluster", and tried to be more careful about it.

    If you need to mark a task as a particular type, you store whatever you like in the .description. I can confirm that info survives background serialization nicely.