Anton
Anton

Reputation: 37

I can't get data with help of NSURLSession

I wrote some test code

-(void)downloadFile
{
   [self getFile:^(id result) {

      if([result isKindOfClass:[NSData class]])
      {
         self.myData=result;
      }

    }];

    NSLog(@"%lu",(unsigned long)[self.myData length]); 
}

-(void)getFile:(void(^)(id result))completionHandler
{
   void(^partCompetionHandle)(NSURL *, NSURLResponse *, NSError *)=^(NSURL *url, NSURLResponse *response, NSError *error){

       if(response==nil){
           completionHandler(error);
           return;
       }

       NSData *data=[NSData dataWithContentsOfURL:url];

       completionHandler(data);  
   };
   self.session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

   NSURL *url=[NSURL URLWithString:@"http://upload.wikimedia.org/wikipedia/commons/7/7f/Williams_River-27527.jpg"];

   NSURLSessionDownloadTask *dataTask =[_session downloadTaskWithURL:url completionHandler:^(NSURL* data, NSURLResponse * response, NSError *  error) {
        partCompetionHandle(data, response, error);

   }];
   [dataTask resume];
}

My datas are zero, when I downloaded theirs this line shows 0

NSLog(@"%lu",(unsigned long)[self.myData length]); 

Upvotes: 0

Views: 55

Answers (2)

Anton
Anton

Reputation: 37

I changed code. But I don't see data

 -(void)downloadFile
    {
    [self getFile:^(id result) {

        if([result isKindOfClass:[NSData class]])
        {
            self.myData=result;
            NSLog(@"%lu",(unsigned long)[self.myData length]);
        }

    }];
  }

I called method downloadFile from main function

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        DownloadFile *donload=[DownloadFile new];

        [donload downloadFile];
    }
    return 0;
}

How can I get data?

Upvotes: 0

vadian
vadian

Reputation: 285039

The classic : As the task is performed asynchronously, the logging of the result is much earlier than the data are downloaded.

Put the log line in the completion block

-(void)downloadFile
{
   [self getFile:^(id result) {
      if([result isKindOfClass:[NSData class]]) {
         self.myData=result;
         NSLog(@"%lu",(unsigned long)[self.myData length]); 
      }
    }];
}

Upvotes: 1

Related Questions