My app have to download many image from web. So I want to provide a button to clear caches of this images.
Are these images save in /Library/Caches ?
I Assuming that there are stored in the /Library/Caches. So I attempt to delete these files by:
filemgr = [NSFileManager defaultManager];
NSError *error;
[filemgr removeItemAtPath: [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] error:&error]
// OR
[filemgr removeItemAtPath:[NSHomeDirectory() stringByAppendingString:#"/Library/Caches"] error:&error];
Both are error with The operation couldn’t be completed. (Cocoa error 513.) in iOS device, but worked in Simulator.
Thank you for answer!
You cant remove "/Library/Caches". You need to remove all items in"/Library/Caches"
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
for (NSString *filePath in [[NSFileManager defaultManager] enumeratorAtPath:path])
{
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:[path stringByAppendingPathComponent:filePath] error:&error];
if (error)
{
NSLog(#"%#",error.description);
}
}
You can not remove direct Cache folder. You have to parse every file from Cache folder and remove them.
Thanks.
Related
when i use simulator,i can find the database file in /documents .but when i use my iPhone to run the project,i can not find the database file.
what time should i create the database file or use this code in my project?
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolderPath = [searchPaths objectAtIndex:0];
NSString *dbFilePath = [documentFolderPath stringByAppendingString:DATABASENAME];
NSFileManager *fm = [NSFileManager defaultManager];
BOOL isExist = [fm fileExistsAtPath:dbFilePath];
if (!isExist) {
NSString *backupDbPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingString:DATABASENAME];
[fm copyItemAtPath:backupDbPath toPath:dbFilePath error:nil];
}
For the first time or the database file does not exist in the documents directory, you have to copy DB file to document directory:
-(void)copyDatabaseIntoDocumentsDirectory{
// Check if the database file exists in the documents directory.
NSString *destinationPath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
// The database file does not exist in the documents directory, so copy it from the main bundle now.
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFilename];
NSError *error;
[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];
// Check if any error occurred during copying and display it.
if (error != nil) {
NSLog(#"%#", [error localizedDescription]);
}
}
}
Ref: http://www.appcoda.com/sqlite-database-ios-app-tutorial/
You can't access the directories of iPhone or iPad. So even if you successfully created a database, you won't see it. You can judge its existence by read data from it.
I am trying to create two log files and replace content in the second file with the content in the first file.
My code for creating log in AppDelegate
NSArray *paths3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory3 = [paths3 objectAtIndex:0];
logPath3 = [documentsDirectory3 stringByAppendingPathComponent:#"console4.log"];
if(![[NSFileManager defaultManager] fileExistsAtPath:logPath3])
[[NSFileManager defaultManager] createFileAtPath:logPath3 contents:[NSData data] attributes:nil];
NSLog(#"path %#",logPath3);
freopen([logPath3 cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory2 = [paths2 objectAtIndex:0];
logPath2 = [documentsDirectory2 stringByAppendingPathComponent:#"console3.log"];
if(![[NSFileManager defaultManager] fileExistsAtPath:logPath2])
[[NSFileManager defaultManager] createFileAtPath:logPath2 contents:[NSData data] attributes:nil];
NSLog(#"path %#",logPath2);
freopen([logPath2 cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
_isFileOneCreated =YES;
code to move content
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSError * err;
if ([filemgr moveItemAtPath:
logPath2 toPath:
logPath3 error: &err])
NSLog (#"Day 3 Move successful");
else
NSLog (#"Day 3 Move failed %#",[err localizedDescription]);
But i get an error 516.
(Cocoa error 516.)" UserInfo=0x16dba220 {NSSourceFilePathErrorKey=/var/mobile/Containers/Data/Application/274E9843-2C8E-45F3-BD41-EA392F50C7AC/Documents/console3.log, NSUserStringVariant=(
Move
), NSFilePath=/var/mobile/Containers/Data/Application/274E9843-2C8E-45F3-BD41-EA392F50C7AC/Documents/console3.log, NSDestinationFilePath=/var/mobile/Containers/Data/Application/274E9843-2C8E-45F3-BD41-EA392F50C7AC/Documents/console4.log, NSUnderlyingError=0x16da63f0 "The operation couldn’t be completed. File exists"}
Help me solve my issue
moveItemAtPath does not allow you to overwrite the file with same name. See this Question Thread.
All you need to do is delete the file at target location before you overwrite with new one. Use the below code. This will do the trick but i advice you to take precaution to have the backup of your file just in case move doesn't work for some unknown reason.
NSFileManager *filemgr = [NSFileManager defaultManager];
NSError * err;
[filemgr removeItemAtPath:logPath3 error:&err];
if ([filemgr moveItemAtPath:logPath3 toPath:logPath2 error: &err])
NSLog (#"Day 3 Move successful");
else
NSLog (#"Day 3 Move failed %#",[err localizedDescription]);
I developed iPhone app in which i got stuck at one point,
What i want to do is,
I want to copy my Database from bundle to folder inside document directory
When i try to create folder inside DocDir it doesn't getting created and it shows error,
Failed to create MyDB.sql file with message 'The operation couldn’t be completed. (Cocoa error 4.)
Here is my code snippet,
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [[paths objectAtIndex:0] stringByAppendingString:#"/NewFolder/"];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:#"MyDB.sql"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:#"MyDB" ofType:#"sql"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
Where i am doing mistake? please help
Thanks in advance.
Try to create directory by following code, may you get help..
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/YourFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])//Check
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Will Create folder
I'm trying to copy a json file from the application bundle to the Document directory, but surprisingly i'm not able to do that. Here's the code:
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [array lastObject];
NSString *path = [docDir stringByAppendingPathExtension:#"themes.json"];
if (![[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSString *themesPath = [[NSBundle mainBundle] pathForResource:#"themes" ofType:#"json"];
NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtPath:themesPath toPath:path error:&error];
if (error)
NSLog(#"Error %#", error);
}
It produces the following error:
Error Domain=NSCocoaErrorDomain Code=513 "The operation couldn’t be completed. (Cocoa error 513.)" UserInfo=0x194a0e90 {NSSourceFilePathErrorKey=/var/mobile/Applications/ACED3EF9-B0D8-49E8-91DE-37128357E509/Frinder.app/themes.json, NSUserStringVariant=(
Copy
), NSFilePath=/var/mobile/Applications/ACED3EF9-B0D8-49E8-91DE-37128357E509/Frinder.app/themes.json, NSDestinationFilePath=/var/mobile/Applications/ACED3EF9-B0D8-49E8-91DE-37128357E509/Documents.themes.json, NSUnderlyingError=0x194a0400 "The operation couldn’t be completed. Operation not permitted"}
After a search i've found this question and tried to modify my code as follows:
if (![[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSString *themesPath = [[NSBundle mainBundle] pathForResource:#"themes" ofType:#"json"];
NSData *data = [NSData dataWithContentsOfFile:themesPath];
BOOL success = [[NSFileManager defaultManager] createFileAtPath:path contents:data attributes:nil];
if (!success)
NSLog(#"Fail");
}
but it doesn't work either. success variable is NO. The last thing i tried was:
[data writeToFile:path atomically:YES];
but still in vain. it returns NO.
I need to note that the issue arises on a device only. On a simulator it works all right.
Can anybody give me a clue?
The first example is correct on one thing:
[docDir stringByAppendingPathExtension:#"themes.json"];
should be:
[docDir stringByAppendingPathComponent:#"themes.json"];
This becomes clear we you read the error message, you see that it tries to write the file to /var/mobile/Applications/ACED3EF9-B0D8-49E8-91DE-37128357E509/Documents.themes.json. Notice that there a . where there should be a /.
The stringByAppendingPathExtension: is used for adding a extension to a file, jpg, txt, html,.....
stringByAppendingPathComponent will add a file to a path, by adding the correct directory separator, you case /.
You second example will definitely fail since the app bundle is readonly.
I try to get my file in my self created Directory in the Documents Directory into a NSData Object like this:
NSString *path = [documentsDirectory stringByAppendingFormat:#"%#%#",#"/",fileName];
NSError* errorr = nil;
NSData *fileData = [NSData dataWithContentsOfFile:path options: 0 error: &errorr];
if (fileData == nil)
{
NSLog(#"Failed to read file, error %#", errorr);
}
else
{
}
But i always get this error:
Failed to read file, error Error Domain=NSCocoaErrorDomain Code=257 "The operation couldn’t be completed. (Cocoa error 257.)" UserInfo=0x156be110 {NSFilePath=/var/mobile/Applications/679253E3-652C-45EE-B589-609E52E4E3B0/Documents/upload/test.xml, NSUnderlyingError=0x156ba7f0 "The operation couldn’t be completed. Permission denied"}
So if i check if the file is readable:
if ([[NSFileManager defaultManager] isReadableFileAtPath: path] == YES)
NSLog (#"File is readable");
else
NSLog (#"File is read only");
i get the result that the file is readable, so why do i get the error if i want to parse that file into NSData?!
UPDATE: i created my file like this:
NSString *filePath = [self dataFilePath:fileName];
[xmlData writeToFile:filePath atomically:YES];
- (NSString *)dataFilePath: (NSString *) path {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"upload"];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory])
[[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:NO attributes:nil error:&error];
NSString *documentsPath = [documentsDirectory
stringByAppendingPathComponent:path];
return documentsPath;
}
UPDATE2: After creating the file, i move it into another Directory with this function:
- (void)moveXmlFilesToUploadDirectory
{
#try {
//Check if FILES_DIR exists
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:FILES_DIR];//filesDir
NSString *uploadDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:UPLOAD_DIR];//filesDir
if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory])
{
NSString *extension = #"xml";
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:NULL];
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;
while ((filename = [e nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[[NSFileManager defaultManager] moveItemAtPath:documentsDirectory toPath:[uploadDirectory stringByAppendingPathComponent:filename] error:NULL];
}
}
}
}
#catch (NSException *exception) {
}
#finally {
}
}
Maybe the Problem is after moving the file! Cause if i try to get my file into a NSData before i move it, everything works...
It seems that you try to copy the whole directory to a destination meant to be a file. The result is that the filepath is a directory path in the end so you can't open it like a file which leads to the permission error message.
You should update your copy code to
while ((filename = [e nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[[NSFileManager defaultManager] moveItemAtPath:[documentsDirectory stringByAppendingPathComponent: filename] toPath:[uploadDirectory stringByAppendingPathComponent:filename] error:NULL];
}
}
to copy every file individually. That will create than the actual file at the destination path intend of a directory.
The chances are high that you don't have the right permissions for that file. Please check the permissions and add read access for the current user or "everyone". You can set the read permissions for your user by the info dialog (cmd + i) or in the terminal with chmod u+r test.xml. Eventually you have to set the owner before with
sudo chown yourusername test.xml
Hope that makes sense.