iOS - Saving multiple images to Documents folder

2020-07-20 13:32发布

问题:

I have this code this code to save an image to the Documents folder.

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,        NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *savedImagePath = [documentsDirectory  stringByAppendingPathComponent:@"savedImage.png"];
    UIImage *image = imageView.image; // imageView is my image from camera
    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:savedImagePath atomically:NO]; 

I am looking for a way to be able to save multiple images as this one keeps over writing the savedImage.png name.

I do not mind looking for it on google or whatever, but I need to know what it is called, since looking with the wrong keywords really delays the world:-)

Cheers

回答1:

You need to change the file name that you are appending to the image documentsDirectory path on line three. Each time you'll need to use a different name that isn't already used. NSFileManager has methods to see if a file exists so you can construct a file name and then test if it exists in that location and if so, increment your duplicate count and try the next one.

if num is an integer you define somewhere and keep around so you know the last one you thought you used (and that you've initialized to 1 somewhere).

// your code to get the directory here, as above

NSFileManager *fm = [NSFileManager ...]

do {
   savedImagePath = [documentsDirectory stringByAppendingPathComponent: 
        [NSString stringWithFormat: @"%@-%d.png", @"savedImage", num]];
   num += 1; // for next time

  if ( ![fm fileExistsAtPath: savedImagePath] )
  {
      // save your image here using savedImagePath
      exit;
  }
} while ( //some kind of test for maximum tries/time or whatever )

you'll have to look up the syntax to get an NSFileManager instance and the exact file exists method signature, but that's the gist of it.



回答2:

If you save file with current dateTime you don't need to worry about same name override problem

-(NSString*)getCurrentDateTimeAsNSString
{
    NSDateFormatter *format = [[NSDateFormatter alloc] init]; 
    [format setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *now = [NSDate date];
    NSString *retStr = [format stringFromDate:now];
    [format release];

    return retStr;
}


回答3:

you can create a new file each time to do that.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"YOURiMAGEfILE.IMAGEeXTENSION"];
NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath: path]) 
    {
        path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"YOURiMAGEfILE.IMAGEeXTENSION] ];
    }

and then you can perform your above operations on the created file.



回答4:

Hope it help You Working For me!!

if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
    {
        let i = Int(arc4random())

        let str = String(i).appending(".png")

        let fileManager = FileManager.default
        let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(str)

        print(paths)

        let imageData = UIImagePNGRepresentation(image)
        fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
    }
    else{
        print("error")

    }