Shouri
Shouri

Reputation: 39

How to put timestamp so that it won't duplicate when saving

I want to put a time stamp so that when I make the app save I can avoid duplicates I am using the code

NSArray *directoryNames = [NSArray arrayWithObjects:@"hats",@"bottoms",@"right",@"left",nil];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder

    for (int i = 0; i < [directoryNames count] ; i++) {
        NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:i]];
        if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
            [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder

        NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:@"hats"]; // "right" is at index 2, per comments & code
        NSString *filePath = [folderPath stringByAppendingPathComponent:@"IMAGE_NAME_HERE.PNG"]; // you maybe want to incorporate a timestamp into the name to avoid duplicates
        NSData *imageData = UIImagePNGRepresentation(captureImage.image);
        [imageData writeToFile:filePath atomically:YES];
    }
} 

How can I put a time stamp or something else?I just want to stop the duplicate so it dosent need to be a timestamp

Upvotes: 2

Views: 1648

Answers (3)

iphonic
iphonic

Reputation: 12717

You can directly use the timestamp, and there is no chance of getting it duplicate. Check the code below

time_t unixTime = (time_t) [[NSDate date] timeIntervalSince1970];
NSString *timestamp=[NSString stringWithFormat:@"%ld",unixTime];

Upvotes: 3

geekchic
geekchic

Reputation: 2431

You can use this NSDate selector:

- (NSTimeInterval)timeIntervalSince1970

It returns the number of seconds since 00:00:00 GMT January 1, 1970.

Example:

time_t getTime = (time_t) [[NSDate date] timeIntervalSince1970];

Which you could store so that you'd have a reference to when a file was saved.

Upvotes: 0

Michael Dautermann
Michael Dautermann

Reputation: 89519

You didn't make it clear but I suspect what you want is to add a date as part of the filename.

To do this, you need to use a "NSDateFormatter" to convert a NSDate object (e.g. today's date?) into a string. Here is a related question that shows how to create that string.

If you don't want to make the date as part of the file or folder name, you can also simply check to see if the file already exists within the folder path. If it does exist, don't write the png file.

Upvotes: 0

Related Questions