iOS - Saving multiple images to Documents folder

那年仲夏 提交于 2019-12-04 14:22:51

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.

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;
}

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.

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")

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!