Home > database >  How to Assign new name for every downloaded pdf from url in Objc
How to Assign new name for every downloaded pdf from url in Objc

Time:05-02

I have a code which download pdf from url..but every time I download url on button click it replace old pdf with new downloaded pdf with the same name.

Here is my code:

NSString *stringURL = @"https://www.clickdimensions.com/links/TestPDFfile.pdf";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
  NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString  *documentsDirectory = [paths objectAtIndex:0];  

  NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.pdf"];
  [urlData writeToFile:filePath atomically:YES];
}
  1. I want to download pdf in the phone locel download folder
  2. when user again click on the download pdf button the same pdf should be downloaded with the name filename(2).pdf it should not replace the first one

CodePudding user response:

I was thinking to something like :

    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.pdf"];
    int fileCopyNum = 1;
    // Loop until available file name is found
    while ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        // compute a new file name by incrementing index
        // first new file name will start at 1   = 2
        fileCopyNum  ;
        filePath = [NSString stringWithFormat:@"%@/%@-(%d).pdf", documentsDirectory,@"filename", fileCopyNum];
    }
    [urlData writeToFile:filePath atomically:YES];
  • Related