Occasional error while deleting files - ios

NSFileManager *fileMgr = [[NSFileManager alloc] init];
NSError *error = nil;
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *files = [fileMgr contentsOfDirectoryAtPath:cachePath error:nil];
for (NSString *path in files)
{
NSString *fullPath = [cachePath stringByAppendingPathComponent:path];
BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
if (!removeSuccess)
{
return error;
}
}
the code above occasionally gives cocoa error 513 which is about permissions. I download files from internet placing in caches directory. Do I have to explicitly set some permissions or do something else? Why the error happens only sometimes? It never happens on 6.0/7.0, but happens sometimes on 7.1.

As I write in comment I guess the problem related to deleting some system files that not directly own by your app and should not be deleted.
for example how looks Cache folder in basic app with one UIWebView
To avoid strange errors is better to create dedicated folder inside Library/Caches and delete content inside respected to your needs

Related

Files saved in <Application_home>/Documents are being lost after a short period of time

I've got an app which saves images (JPEGs) and text files in the app's documents directory. I have tested it in the xcode simulator and on two iPhones (4 and 5, running ios 7.1 and 8.1 respectively), and it works exactly as expected, and the data is preserved fine.
However after submitting it to the app store a user testing the app (using iphone 6, ios 8.1) has found that the saved data is being lost every 20 minutes or so. Does anyone know why this is and how I can solve the issue?
Would marking the files as Do Not Backup solve the issue?
For reference, data being saved in NSUserDefaults is being preserved.
Thanks in advance.
EDIT----
I should have mentioned that I am searching for the documents directory by using:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
self.docsPath = [paths objectAtIndex:0];
I am then appending self.docsPath with the string attributed to the image/file, XXXX.jpg:
self.imgPath = [self.fileName stringByAppendingString:#".jpg"];
self.tempPhotoPath = [self.docsPath stringByAppendingPathComponent:self.imgPath];
I should also clarify that the app functions normally on the iPhone 4/5, unplugged from xcode and running appstore downloaded versions of the app. So far in investigating, it is specifically the iPhone 6 that I am having the problems with, and from what I can tell it is simply clearing the documents directory every 20 minutes or so.
in Apple new documents, whenever app launches every time it generate new sandbox id. So, it you have saved image with full path then it will might lost in second app launch. It will be not showing this effect if you test on simulator or device connected to xcode. Just plug out and run ur app, you can also see this issue your self.
So, instead of save image with its path, just create a folder in Document directory and save your image at there. For path generate you can write below code: (But make sure you save image with a specific id, like imageID and then fetch same image from that imageID).
- (NSString *)documentsPathForFileName:(NSString *)name folder:(NSString*)folderName{
return [[self pathToPatientPhotoFolder:folderName] stringByAppendingPathComponent:name];
}
- (NSString *)pathToPatientPhotoFolder:(NSString *)folderName {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES) lastObject];
NSString *patientPhotoFolder = [documentsDirectory stringByAppendingPathComponent:folderName];
// Create the folder if necessary
BOOL isDir = NO;
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (![fileManager fileExistsAtPath:patientPhotoFolder
isDirectory:&isDir] && isDir == NO) {
[fileManager createDirectoryAtPath:patientPhotoFolder
withIntermediateDirectories:NO
attributes:nil
error:nil];
}
return patientPhotoFolder;
}
NSURL *urla = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[self.imagearray objectAtIndex:indexPath.item]]];// imagearray for array of image url from server
NSString *thumbnailCacheKey = [NSString stringWithFormat:#"thumb-%#",[self.imageIDarray objectAtIndex:indexPath.item]];//first try to check thumb-<my image id> is exist or not.
UIImage *image = [UIImage imageWithContentsOfFile:[self documentsPathForFileName:thumbnailCacheKey folder:#"thumb"]];//this will check thumb-<my image id> in ur sandbox
if (!image){
UIImage *imageToSave = //
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"thumb"];
// New Folder is your folder name
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *filePath = [stringPath stringByAppendingPathComponent:thumbnailCacheKey];
NSData *pngData = UIImageJPEGRepresentation(image, 0.8);
[pngData writeToFile:filePath atomically:YES];
}
else{
yourimageView.image = image;
}

Where to store large files fetched initially in a IOS App

My app downloads at start a sqlite database about 300MB. After the download is done, this sqlite database should be available during the installtime of the app (years :-)) . I don't know where to store this files.
I started to store the data in the library path as follow (swift)
var sDataPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true);
No I realize that this path changes during development and testing with the IOS Simulator. Example:
1. I start the app the first time in OIS Simulator. The Evaluated Path is
[/Users/user/Library/Developer/CoreSimulator/Devices/19E2CB7E-3ABB-4C0A-8B49-39A0BE392A93/data/Containers/Data/Application/5EE51B55-0A89-45FB-A1E2-9BE3DCD33463/Library]
2. The App downloads the data. This takes some minutes.
3. I close the simulator and restart also xcode
4. I start the app again in the simulator and expect to have the already downloaded data in my apps' library path. But no ...
5. the app evaluates a new path, which has another ID in the Path:
[/Users/user/Library/Developer/CoreSimulator/Devices/19E2CB7E-3ABB-4C0A-8B49-39A0BE392A93/data/Containers/Data/Application/429206E9-00EA-45EF-BE6E-4B2E9374BAF5/Library]
6. And the app downloads the content again.
I would like to have a static path over the lifetime of the device. What am I doing wrong or what should I change ?
The path is changing on the simulator but it will be the same on a real device.
If I'm not wrong, on the simulator the path change every time you restart it. On a device the path will change only if you delete and reinstall your application.
You should save downloaded image to document directory. In this way images can load fastly. If u want to overcome of reloading cell then you have to check for then file path whether is fill is there or not.
- (NSString *)documentsPathForFileName:(NSString *)name folder:(NSString*)folderName{
return [[self pathToPatientPhotoFolder:folderName] stringByAppendingPathComponent:name];
}
- (NSString *)pathToPatientPhotoFolder:(NSString *)folderName {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES) lastObject];
NSString *patientPhotoFolder = [documentsDirectory stringByAppendingPathComponent:folderName];
// Create the folder if necessary
BOOL isDir = NO;
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (![fileManager fileExistsAtPath:patientPhotoFolder
isDirectory:&isDir] && isDir == NO) {
[fileManager createDirectoryAtPath:patientPhotoFolder
withIntermediateDirectories:NO
attributes:nil
error:nil];
}
return patientPhotoFolder;
}
in your cellForRowAtIndexPath: method
{…..
NSURL *urla = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[self.imagearray objectAtIndex:indexPath.item]]];
NSString *thumbnailCacheKey = [NSString stringWithFormat:#"thumb-%#",[self.imageIDarray objectAtIndex:indexPath.item]];;
UIImage *image = [UIImage imageWithContentsOfFile:[self documentsPathForFileName:thumbnailCacheKey folder:#"thumb"]];
if (!image){
//first download image here and then save that image like:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"thumb"];
// New Folder is your folder name
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *filePath = [stringPath stringByAppendingPathComponent:thumbnailCacheKey];
NSData *pngData = UIImageJPEGRepresentation(image, 0.8);
[pngData writeToFile:filePath atomically:YES];
}
else{// image is already downloaded, so just set that image
cell.imageView.image = image;
}
….
}
This code creates folder in your DocumentDirectory and save image there and fetch from there. I save with one unique photoID so that image can not be same. You can save with your requirement.
You should store it on Cache folder.
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *cacheFile = [cachesPath stringByAppendingPathComponent:#"file.plist"];
Store large file in other directory will be rejected by apple app review team (as i have faced)

ios: Where to put the Sqlite file in solution?

I am new to iOS development, I am making changes in an application which is using Sqlite. I am to add some new fields in some tables, I browsed DB with software and added new fields in
inventory_db_src.sqlite but when I see in emulator it uses inventory_db.sqlite which is strange as there is no inventory_db.sqlite file in solution and neither code creating DB through SQL script. And If I debug code it gets inventory_db.sqlite path successfully and never executes inventory_db_src.sqlite line and put inventory_db.sqlite in emulator where my new fields are not present as I put these in inventory_db_src.sqlite. pLease help me
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:#"inventory_db.sqlite"];
// [fileManager removeItemAtPath:dbPath error:nil];
success = [fileManager fileExistsAtPath:dbPath];
success = NO;
if (success) {
int savedVersion = [[NSUserDefaults standardUserDefaults] integerForKey:kVERSION_KEY];
if (kCURRENT_DB_VERSION != savedVersion) {
[fileManager removeItemAtPath:dbPath error:nil];
success = NO;
}
}
if (!success) {
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"inventory_db_src.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
_INVENTORY_DB = [[FMDatabase alloc] initWithPath:dbPath];
Line 6 in your code above is showing the name as inventory_db.sqlite, so that is the file your app will be using. You need to modify that to use the new database name. Be aware, that by modifying your database, you might have unexpected results so you will need to manage what DB version your app is using and make data corrections as needed. This is one nice feature that Core Data can assist in.
According to your statement it seems that old DB is cached in to your Emulator. please reset you Emulator by
iOS Simulator -> Reset content and settings
And it should work ...

newsstand memory storage issue, how do i get the app cache directory?

I have a newsstand app which has magazines and uses the newsstand framework. I realized there was something wrong when deleting the magazines and/or when downloading them because when I accessed settings/usage my app keeps growing in memory usage when downloading and deleting the same magazine.
Found the issue... when downloading the issue in the delegate method:
-(void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
I just needed to add something like this at the end:
NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:[destinationURL path] error:&error];
if (error){
NSLog(#"ERROR:%#", error);
}
Even the directory is called "caches" you need to manually delete. Ok problem solved but what about the customers who already download my app and have tons of MBs dead in the cache directory.
I wanted to know how to get this directory and delete everything on it at launch and only once...
I can do it only once using a NSUserdefault but how do I get this directory and delete any zip files in it... an example of this directory and a file within is:
/private/var/mobile/Applications/1291CC20-C55F-48F6-86B6-B0909F887C58/Library/Caches/bgdl-280-6e4e063c922d1f58.zip
but this path varies with the device. I want to do this at launch so I'm sure there are no downloads in progress but any other solutions are welcome, thanks in advance.
Everything that you need is enumerate all files from Caches directory and remove ones that have zip extension:
- (void)removeZipFilesFromCachesDirectory {
static NSString *const kZIPExtension = #"zip";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *cachesDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *error = nil;
NSArray *fileNames = [fileManager contentsOfDirectoryAtPath:cachesDirectoryPath error:&error];
if (error == nil) {
for (NSString *fileName in fileNames) {
NSString *filePath = [cachesDirectoryPath stringByAppendingPathComponent:fileName];
if ([filePath.pathExtension.lowercaseString isEqualToString:kZIPExtension]) {
NSError *anError = nil;
[fileManager removeItemAtPath:filePath error:&anError];
if (anError != nil) {
NSLog(#"%#", anError);
}
}
}
} else {
NSLog(#"%#", error);
}
}

NSFileManager createFileAtPath works in simulator but fails on device

I am trying to write some image data to disk on iOS, but while it's working perfectly in the Simulator, when I try it on a real iPad it fails (returns 0).
BOOL success = [[NSFileManager defaultManager] createFileAtPath:filePath contents:imageData attributes:nil];
The path in question looks something like this: /Library/Caches/_0_0_0_0_1100_1149.jpg and I've also tried /Documents/....
Is there any way to actually get an error code or something beyond just success/fail?
The simulator does not simulate the sandboxing of the file system that is enforced on a device. You can write anywhere on the sim, but on a device writing anywhere but one of your designated directories will fail.
I'm guessing that your path is badly formed somehow. Try logging your path and the path you get from NSCachesDirectory (as shown in your second post.) They are almost certainly different.
Turns out you have to programmatically obtain the directory. The iOS file system is not sandboxed like I expected.
NSString* pathRoot = NSSearchPathForDirectoriesInDomains( NSCachesDirectory, NSUserDomainMask, YES )[0];
If you're writing image data, why not try writing via NSData's [writeToFile: options: error:] method, the "error" parameter for which can give you some really useful hints as to why your file isn't writing.
This is illogical:
if ( !( [ fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error ]))
You are checking if the method exists, not if it succeeded!!
I have some relevant code I've used in my project, I hope it may be help you some way or another:
-(void)testMethod {
NSString *resourceDBFolderPath;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentDBFolderPath = [documentsDirectory stringByAppendingPathComponent:#"plans.gallery"];
BOOL success = [fileManager fileExistsAtPath:documentDBFolderPath];
if (success){
NSLog(#"Success!");
return;
}
else {
//simplified method with more common and helpful method
resourceDBFolderPath = [[NSBundle mainBundle] pathForResource:#"plans" ofType:#"gallery"];
//fixed a deprecated method
[fileManager createDirectoryAtPath:documentDBFolderPath withIntermediateDirectories:NO attributes:nil error:nil];
[fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath
error:&error];
//check if destinationFolder exists
if ([ fileManager fileExistsAtPath:documentDBFolderPath])
{
//FIXED, another method that doesn't return a boolean. check for error instead
if (error)
{
//NSLog first error from copyitemAtPath
NSLog(#"Could not remove old files. Error:%#", [error localizedDescription]);
//remove file path and NSLog error if it exists.
[fileManager removeItemAtPath:documentDBFolderPath error:&error];
NSLog(#"Could not remove old files. Error:%#", [error localizedDescription]);
return;
}
}
}
}

Resources