How to save a unique image name in the document directory

In my iOS app, I'm stuck in a task. I need to take a pic from the camera and save it in the document directory. The problem is that I want to keep a unique image name. I tried to add the current time with a name. but there is a problem with the length for saving the image. Please suggest me how I can accomplish this task.

thanks

+4
source share
5 answers

Given a suggested name like NString *name = @"Lake" :

 NSString *myUniqueName = [NSString stringWithFormat:@"%@-%u", name, (NSUInteger)([[NSDate date] timeIntervalSince1970]*10.0)]; 

EDIT: updated so that the only chance for a duplicate is the same original name sent within 100 ms of the first (almost impossible, in my opinion, if this is a problem, use 100 instead of 10)

+7
source
 -(NSString*)getFilePathToSaveUnUpdatedImage { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *directory = [paths objectAtIndex:0]; for (int i = 0 ; TRUE ; i++) { if(![[NSFileManager defaultManager]fileExistsAtPath:[NSString stringWithFormat:@"%@/UnUpdatedItems/Image%d.png", directory , i]]) return [NSString stringWithFormat:@"%@/UnUpdatedItems/Image%d.png", directory , i]; } } 
+3
source

Try it just to form a date and save the image.

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSDate *now = [NSDate date]; NSString *theDate = [dateFormat stringFromDate:now]; [data writeToFile:[NSString stringWithFormat:@"%@.png",theDate] atomically:YES]; 
+3
source

use this line of code to specify a name.

 [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterShortStyle]] 

This works for me for the same problem.

+1
source
 -(NSString*)getImagePathName { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *directory = [paths objectAtIndex:0]; for (int i = 0 ; TRUE ; i++) { if(![[NSFileManager defaultManager]fileExistsAtPath:[NSString stringWithFormat:@"%@/Image%d.png", directory , i]]) return [NSString stringWithFormat:@"%@/Image%d.png", directory , i]; } } 
0
source

Source: https://habr.com/ru/post/1484640/


All Articles