0

This is my code to download the pdf files using NSUrlConnection and i downloading them to the document directories.

-(void)startDownloadFile:(UIButton *)sender
{
    ResourceTelephones * resource = [array objectAtIndex:sender.tag];

    NSString * currentURL = resource.website;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:currentURL]];

    NSURLConnection *conn = [[NSURLConnection alloc] init];
    (void)[conn initWithRequest:request delegate:self];

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{
        NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:currentURL]];
        dispatch_sync(dispatch_get_main_queue(), ^{
        });
       NSString * filePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:@"myPDF%ld.pdf",(long)sender.tag]];
        NSLog(@"PDF path: %@",filePath);
        [data writeToFile:filePath atomically:YES];

    });

}

and am viewing the file using below code

-(void)viewAction:(UIButton *)sender
{
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [searchPaths objectAtIndex:0];
    NSURL *url =  [NSURL fileURLWithPath:[documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"myPDF%ld.pdf",(long)sender.tag]]];
    if (url) {
        // Initialize Document Interaction Controller
        _documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:url];

        // Configure Document Interaction Controller
        [_documentInteractionController setDelegate:self];

        // Preview PDF
        [_documentInteractionController presentPreviewAnimated:YES];
    }
}

now i want to put the progress bar for each cell corresponding to each pdf file for downloading..and after downloading the file..i want to change the name of the button "download" to "view" and change the corresponding action..and one more thing i should able to view the file after re opening the application because it is already downloaded..

sash
  • 8,423
  • 5
  • 63
  • 74
  • 1
    So are you using the `NSURLConnection` delegate methods and why are you using `dataWithContentsOfURL:`? – Wain Apr 17 '14 at 09:59

3 Answers3

0

For progress bar updates, use NSURLConnection delegates,

Example:

 (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
      //here you will get total length 
      totalLength = [response expectedContentLength];
    }

    (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
    {
      // here calculate the downloaded length
      [self.pdfData appendData:data];
      //calculate downloaded percent
      progress = ([self.pdfData length] * 100) / totalLength;
      //and update the progress bar
    }

    (void)connectionDidFinishLoading:(NSURLConnection *)connection 
    {
      //save file here
      //flip the corresponding button to view here
    }

And to view the downloaded pdf file, check the file is already downloaded

Example:

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
  // show the view button
}
else
  //start download
Sathish Kumar
  • 219
  • 1
  • 10
  • i think that "progress.progress = ([self.pdfData length] * 100) / totalLength; "will give the reference to last row right? so how can we get the each cell reference to add a progress view in that delegate method.. – user3540000 Apr 18 '14 at 04:20
  • i think its possible if we create an indexPath and a uitableviewCell in that method..but its not possible for me create them..can u? – user3540000 Apr 18 '14 at 04:23
  • @user3540000 take a look at this https://developer.apple.com/library/ios/samplecode/LazyTableImages/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009394 – Sathish Kumar Apr 18 '14 at 05:37
0

To calculate the progress of downloading using NSURLconnection use the following delegate function.

-(void) connection:(NSURLConnection *) connection
        didReceiveResponse:(NSURLResponse *) response
        {
            //In this function you will get the total size of PDF data you are receiving
            fTotalSize=(float)[response expectedContentLength];

            if(!datWebServiceData)
        datWebServiceData =[[NSMutableData alloc]init];

           //datWebServiceData = [[NSMutableData data] retain];
           [datWebServiceData setLength: 0];
        }

-(void) connection:(NSURLConnection *) connection
        didReceiveData:(NSData *) data
       {
         //Here calculate the progress
        float val=(((float) [datWebServiceData length] / (float) fTotalSize))*100;

        lblProgress.text=[NSString stringWithFormat:@"%0.0f%%",val];
       }

lblProgress.text will show the progress of downloading and datWebServiceData is the NSData which will contain the whole data of PDF.

Now to show progress for each cell, save the connection object in NSMutableArray. Then check for the connection object of delegate and all connection objection in array, if they matched then take the array index and then update the entry of that cell accordingly.

svrushal
  • 1,612
  • 14
  • 25
0

firstly create a property of UIButton as below-

@property (strong,nonatomic) IBOutlet UIButton *btn;

Then make the connectivity of it. Also in viewDidLoad method do as follow-

[_btn setTitle:@"DOWNLOADING" forState:UIControlStateNormal];

[_btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

Therefore ,in your startDownloadFile method add following below-

    NSLog(@"PDF path: %@",filePath);
    [data writeToFile:filePath atomically:YES];
    /* ADD BELOW LINE */
    [_btn setTitle:@"VIEW" forState:UIControlStateNormal];

Then for buttonClicked: method as-

-(void)buttonClicked:(UIButton *)sender
{
  if([sender.titleLabel.text isEqualToString:@"VIEW"])
  {
    /* Now as title is VIEW so call viewAction method */
    [self viewAction:sender]
  }
  else
  {
    /*When tapped in DOWNLOADING mode nothing will happen */
  }
}
nikhil84
  • 3,235
  • 4
  • 22
  • 43