简体   繁体   中英

NSURLSessionDataTask and handler block

I'm developing a library that gets json data from a server, and I'm using NSURLSessionDataTask . In order to test my library I created a new project that calls this library method.

typedef void (^CompletionBlock)();
// More stuff...
- (void)downloadAllPodcastsMetadataWithCompletionHandler:(CompletionBlock)block{

   NSURL *url = [NSURL URLWithString:@"MyServerURL"];

   NSURLSessionDataTask *dataTask = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
     // Connection and response handling stuff...
     // When my data is saved, executes the block parameter

     dispatch_async(dispatch_get_main_queue(), ^{
        block();
     });
   }
   [dataTask resume];
}

EDIT: I forgot to put [dataTask resume] here, but it's in my code. Sorry.

EDIT 2: So, as some of you have said, i changed dispatch_sync with dispatch_async. But the result is the same :(

In my test project i call this method like this.

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

[manager downloadAllPodcastsMetadataWithCompletionHandler:^{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}];

But the network activity Indicator never shows off. It's like the block parameter never executes.

It's because it executes the NSURLSessionDataTask logic inside a library and then I should use something else instead dispatch_sync ?

I already checked NSURLSessionDataTask not executing the completion handler block and I think I do the same. If it helps, manager is a Singleton . Any thoughts?

Thank you.

You need to start the download with [dataTask resume]; .

You need to add [dataTask resume]; and also add this in completion handler dispatch_async(dispatch_get_main_queue(), ^{ [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; });

I tested some code.

Dispatch_sync won't work.

dispatch_sync(dispatch_get_main_queue(), ^{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
});

Dispatch_async worked for me. But I had to put the code on veiwWillAppear. Not sure what's going to happen using it inside a block...

dispatch_async(dispatch_get_main_queue(), ^{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
});

Well, i'm dumb.

There was an error in my previous code i didn't notice, so the completion block war never executing. That is what happens when someone has too much confidence in his code.

Sorry for bothering you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM