I'm trying to move all of the documents that reside in the NSDocumentDirectory to the NSCachesDirectory, and then delete all of those NSDocument files upon the first app launch of my next version update to my app. The only reason I'm doing this is to abide by Apple's iOS data storage guidelines, as my app update was rejected for saving .PDF files to the NSDocumentsDirectory (I have no clue why, because the app has never been rejected for this until this update (app is almost 2 years old, and I have been saving .PDFs this way since day 1), maybe I got a strict reviewer?)
I need to move all of the user's already downloaded .PDF files to the NSCachesDirectory and then delete them from the NSDocumentDirectory.
Is there a simple way this can be accomplished?
Thank you in advance for any help provided.
I tried this:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSUserDefaults *Defaults;
int launchCount;
Defaults = [NSUserDefaults standardUserDefaults];
launchCount = [Defaults integerForKey:@"launchCount" ] + 1;
[Defaults setInteger:launchCount forKey:@"launchCount"];
[Defaults synchronize];
if(launchCount == 1) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *path2 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *dest = [path2 objectAtIndex:0];
NSArray *Contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:&error];
for(NSString *source in Contents)
{
if(![fileManager moveItemAtPath:source
toPath:dest
error:&error])
{
//TODO: Handle error
NSLog(@"Error: %@", error);
}
}
}
But I'm getting this error in the console:
NSFilePath=Test.pdf, NSDestinationFilePath=/Users/Charley/Library/Application Support/iPhone Simulator/5.1/Applications/96EB01D1-81B7-4ECE-B337-D2D663969EE3/Library/Caches, NSUnderlyingError=0xb566d50 "The operation couldn’t be completed. File exists"
Yes, use NSFileManager:
Get your documents path, and your caches path. Iterate over all the file, and move them using NSFileManager
- (void) moveAllDocs {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSString *sourceDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *destinationDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:sourceDirectory error:&error];
for(NSString *sourceFileName in contents) {
NSString *sourceFile = [sourceDirectory stringByAppendingPathComponent:sourceFileName];
NSString *destFile = [destinationDirectory stringByAppendingPathComponent:sourceFileName];
if(![fileManager moveItemAtPath:sourceFile toPath:destFile error:&error]) {
NSLog(@"Error: %@", error);
}
}
}