How to pass parameter in NSarray in url NSURLSessionDownloadTask

0

I am creating a UITableView to load the bookmarks that are saved in NSUserDefaults, the values are the IDs. ex. 34, 45, 55 ...

I am creating the url and passing parameter through an NSMutableArray. (34, 45, 55). this way.

    NSString * porGeral = [NSString stringWithFormat:@"http://.../api/listarFavoritos.php?listaCli=%@", @"34, 45, 55"];


    url = [NSURL URLWithString:porGeral];

    NSLog(@"%@", porGeral);

    NSURLSession * session = [NSURLSession sharedSession];

    NSURLSessionDownloadTask * task =
    [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        NSData * jsonData = [[NSData alloc] initWithContentsOfURL:location];
        news = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];

        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"%@", news);
            [self.tableView reloadData];
            [self.progressView removeFromSuperview];

        });
    }];
    [task resume];
}

The Error Displayed:

  

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

Your I pass this way the url in the browser does not display the error, so I could identify that this error is in the NSURLSessionDownloadTask.

Any suggestions?

Thanks everyone.

    
asked by anonymous 15.11.2017 / 02:56

1 answer

1

The error occurs when passing a null parameter to the JSONObjectWithData method.

Probably the file download is failing and when the completionHandler is called the value of location is nil .

As a good practice, always add exception handling. This not only prevents crashes, but also helps to identify the root cause of the problem:

[session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    if (error) {
        NSLog(@"Error loading URL: %@", error);
        return;
    }

    NSData *data = [[NSData alloc] initWithContentsOfURL:location];
    if (!data) {
        NSLog(@"Cannot create data from URL");
        return;
    }

    NSError *jsonParsingError = nil;
    news = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParsingError];
    if (jsonParsingError) {
        NSLog(@"Error parsing JSON: %@", jsonParsingError);
        return;
    }

   //... 
}];

If the execution reaches the end of the block, news contains an object, but there is no guarantee that it is of type array since JSONObjectWithData: can return other types, such as NSDictionary .

Another tip, if you do not really need to download, use the dataTaskWithRequest method instead of downloadTaskWithURL, since it already returns an object of type NSData.

    
15.11.2017 / 14:37