Error while deleting the file - ios

While deleting existing the file with this command:
[[NSFileManager defaultManager] removeItemAtPath:self.sourceFileName error:&error];
I got the following error
Error: ImageIO: CGImageReadCreateDataWithMappedFile 'open' failed '/Users/asdasd/Library/Application Support/iPhone Simulator/7.1/Applications/DD251D7D-F0AF-40E1-A033-F221623D589D/Library/ScanSession/Source/page3.jpeg
error = 2 (No such file or directory)'
This happens while I copied pic from album into app folder. The most interesting thing is that file exists, but not fully copied. Is there a way to check wether file is file operation completed?

check weather your file & Directory available
for (NSString *filename in files) {
NSString *path = [yourPath stringByAppendingPathComponent:yourFileName];
BOOL isDir;
if([[NSFileManager defaultManager] fileExistsAtPath:yourPath isDirectory:&isAvilDir] && isAvilDir){
NSLog(#"%# Check is a directory", your path file);
}
else {
NSLog (#"%# Check is a file",your path file);
}
}

I have a similar problem right now, and it seems as though when you delete a file that certain other methods you may have called immediately prior may actually not have completed yet. I'm considering delaying the actual deletion of files to allow for background processes to complete.

Solved it 2 yars ago. Forgot to post & close the question. It was caused by another thread, where the file was deleted first. I think its one of the standart mutlithreading issues while working with CoreData

Related

How to remove file from cache directory in iphone

I am working in a camera app where I can record video and save that in the directory like this:
file:///var/mobile/Applications/2683FFEC-63AB-4004-831B-DE38053CA472/Library/Caches/0C2E7E7C-5D78-4989-9C8E-259B3595BAC8-6498-0000042F24AB2D98.mov
when I go to the camera application I can see the video, but I want to delete this video when I quit the app, I did this so far
NSFileManager *fileManager = [[NSFileManager defaultManager];
[fileManager removeItemAtPath:THEABOVEURL error:&error];
but nothing happens and says cocoa error 4.The operation couldn’t be completed. No such file or directory
But I am sure that the file exists as I can play the video using the exact url mentioned above, what should I do now?
Cocoa Error 4 means
NSFileNoSuchFileError = 4, // Attempt to do a file system operation on a non-existent file
so it looks like that file just doesn't exist.
You may want to be sure that the file exists when you're going to delete it, maybe there is something wrong in the url that you are using?
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error
it takes a string as first parameter, I see on your code
[vedioPaths objectAtIndex:THEABOVEURL]
it looks like THEABOVEURL should be an index, and vedioPaths contains all the NSString representing the path of the files, Add some NSLog to see if these variables contain the right information to delete the file.
Ok, I solved it my way, I was trying to delete an url where the
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error
method wants NSUrl as parameter I converted this string as url and used this method
NSURL *urlfromString= [NSURL URLWithString:ABOVEURL];
[fileManager removeItemAtURL:urlfromString error:&error];
This solved my problem

Moving data from bundle to user doc folder not responding accurately

I have an app that has several in app purchases in it and it also includes one free mp3 when the get the app in the first place and we have the list of mp3 they can play from when purchased and if they want to stream it and we also have a saved session section where they can move it offline and still be able to listen to it only here they can loop and do other things that would incur huge data costs.
The process goes like this I load the mp3 into the bundle and then upon opening the saved sessions view it checks to see if this file exists there if it doesn't then it copies it from the bundle location to the sandbox loacation and then proceeds normally so if it wiped out it will automatically recover itself from the bundle location.
The problem is this it wont't reload at all until at least one other file has been saved no matter what I do actvity wise in the app it just won't move that track in from the bundle UNTIL another track gets moved in first and I restart the app then the next time I go in I notice the slight delay of about a second and it is there in all its glory so I know I am close but I can't figure out why it won't initially do it.
Maybe someone out here can see what I ma missing it was late when I wrote the code so I will go for that as an excuse anyway here is the snippet of code I am working with
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dataPath = [docDir stringByAppendingPathComponent:#"Sessions"];
NSFileManager *filemgr = [NSFileManager defaultManager];
NSString *freeMp3FilePath = [dataPath stringByAppendingPathComponent:FREEMP3];
// Check if the file already exists
DLog(#"%#",freeMp3FilePath);
if (![filemgr fileExistsAtPath: freeMp3FilePath]){
DLog(#"File Not Found");
NSString *freeMP3Address = [[NSBundle mainBundle] pathForResource:#"m-app_0129instantconfidencehd" ofType:#"mp3"];
if([filemgr copyItemAtPath:freeMP3Address toPath:freeMp3FilePath error:nil]) {
DLog(#"File Copied");
} else {
DLog(#"File Not Copied %# %#",freeMp3FilePath,freeMP3Address);
}
}
In the log I see the "File Not Found" message and then I see the "File Not Copied" and the two paths do show up and look just as expected as seen here
2013-06-06 10:37:00.092 IMOB[51674:907] <SavedViewController.m:(57)> File Not Found
2013-06-06 10:37:00.097 IMOB[51674:907] <SavedViewController.m:(62)> File Not Copied /var/mobile/Applications/6D5463FF-4106-479A-8E77-16BD24B22CCF/Documents/Sessions/m-app_0129xxxhd.mp3 /var/mobile/Applications/6D5463FF-4106-479A-8E77-16BD24B22CCF/IMOB.app/m-app_0129xxxhd.mp3
This entry show nothings is in the directory and this also is the case if I shut down the app and restart it
2013-06-06 10:37:00.113 IMOB[51674:907] <SavedViewController.m:(169)> CURRENT ICON ARRAY COUNT :0
Ok hopefully this is something easy
Jeff
You should have added the error parameter when copying the file and checked what it contained...
Before you copy the file, ensure the destination directory exists using createDirectoryAtPath:withIntermediateDirectories:attributes:error:.

NSFileWrapper fails when from iCloud and works from local directory

I have a problem syncing NSFileWrapper documents with iCloud. I am able to create my wrapper and save it to my ubiquitous container.
When I try to read it from the device that created it, it works. When I try to read form another device that got it from iCloud, it crashes.
Some code:
This function to add a wrapper container with a NSString
- (void) addNSString:(NSString*)_string toFileWrapper:(NSFileWrapper*)_wrapper forKey:(NSString*)_key {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_string];
if(data) {
[_wrapper addRegularFileWithContents:data preferredFilename:_key];
}
}
And then here is how I decode it:
- (id) unarchiveObjectFromWrappers:(NSDictionary*)_wrappers withKey:(NSString*)_key {
id value = nil;
NSFileWrapper *wrapper = [_wrappers valueForKey:_key];
if(wrapper) {
NSData *data = [wrapper regularFileContents];
if(data) {
value = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
}
return value;
}
The decoding part works on one device and not on the others (EXC_BAD_ACCESS when the NSKeyedUnarchiver tries to unarchive from the NSData. The NSData seems good, it has the proper length and everything but when I try to log its datas for example it crashes).
My guess is that the NSFileWrapper doesn't download its full content, only its structure and that I have to do something to make it available. But I don't know what.
Any ideas?
========
Edit:
NSURLUbiquitousItemIsDownloadedKey says that the file is downloaded BUT if I try to copy it to the sandbox it fails with this error: "The operation couldn’t be completed. Bad file descriptor"
So the file is either not uploaded properly to iCloud or not downloaded properly...
It drove me crazy too. The solution is rather simple, yet totally undocumented by Apple. You must download the file specifically. Only the file wrapper is downloaded automatically, but not its contents. That's why the check says the file exists.
Before copying the file over, call something like this:
[[NSFileManager defaultManager]startDownloadingUbiquitousItemAtURL:cloudURL error:nil];
Related: Cannot sync simple text file with iCloud (bad file descriptor)

Invalidating QLPreviewController "cache"

QLPreviewController seems to cache file contents based on the local file's URL. In my application, the file contents can be updated remotely and would cause the new contents to be downloaded.
If I view a file in QLPreviewController, update it remotely, then re-preview it, the file does not show up as updated.
The file is definitely updated on disk, and other controls show the correct updated file.
The workaround I'm using right now is to basically move a file when it's previewed to a unique filename (using timestamp), which will of course not be in the QLPreviewController's cache. However, this has other repercussions, for example, if the app is killed or it crashes (god forbid), I won't know "where" to find the downloaded file.
I'm looking for less invasive hacks, or solutions to making QLPreviewController refresh its cache. The APIs don't seem to expose anything, so don't be afraid to submit a hack if it's less gross than the one I've presented above (not including copying/moving the file to a guaranteed unique URL, which I am already utilizing).
Just ran into this issue myself. I solved it by recreating the QLPreviewController each time I reload an item with the same name as the currently viewed item. Creating a new QLPreviewController clears the cache.
I know this is an old question but someone might have the same problem and find this answer helpful.
You should use refreshCurrentPreviewItem after downloading complete
I had the same problem. Opening a locally generated CSV file.
I have my _previewController* setup as a #property of my controller. Then what i did:
- (void)viewDidLoad
{
[super viewDidLoad];
self.previewController = [[QLPreviewController alloc] init];
_previewController.delegate=self;
_previewController.dataSource=self;
}
- (void)previewCSV
{
[_previewController reloadData]; // this triggers a reload
[self presentModalViewController:_previewController animated:YES];
}
IN other solution that comes to mind (not tested).
Depending on your URL, you could add something like http://url?time=123456 to your URL. Like this you change the URL but without side effect. The time (or any other parameter) you can change on each request.
It's the ugliest bug in iOS. Cache management in iOS 5 and beyond. I think is the same reason that makes iCloud buggy, Share-at-Home crashing and so on. Bad cache managements and so worst synchronization systems.
Well, my solution for this was to store the download file in a folder and use the current date to name the folder. It is equivalent to #Rogier's solution, but this works always. You get a name for the folder, for example, with [[NSDate date] description]. Instead of saving the file replacing the old one, you delete previous file, delete previous folder and save new file in a new folder. It's working fine for me.
Just remove all files from tmp directory like this:
- (void)clearCache
{
NSString *tempPath = NSTemporaryDirectory();
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:tempPath error:nil];
NSFileManager *fileManager = [NSFileManager defaultManager];
for (int i = 0; i < [dirContents count]; i++) {
NSLog(#"Directory Count: %i", [dirContents count]);
NSString *contentsOnly = [NSString stringWithFormat:#"%#%#", tempPath, [dirContents objectAtIndex:i]];
[fileManager removeItemAtPath:contentsOnly error:nil];
}
}

fileExistsAtPath: returning NO for files that exist

At a point in my code fileExistsAtPath: is returning NO for files that I have confirmed exist. I've been scratching my head at this and can't figure out why its not working, so changed it to this code as this directory absolutely exists but if it doesn't gets created anyway.
NSError* err = nil;
NSURL *dir = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create: YES
error:&err];
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:[dir absoluteString]];
After running this code the application directory folder exists and err is 0, yet exists is NO.
How can this be?
TIA
You should use [dir path], not [dir absoluteString].
I was bashing my head against the wall for a few hours. Apparently on each and every run in xcode (on simulator) the app directory path was changing. The UUID part of it.
So instead of storing the fullpath I ended up persisting the path postfix
and prefixing that with whatever storage class is implied: temporary, cached
or documents :-[ You realize why you have to sometimes run on device
even if you don't explore the depths of Metal, GLES or multitouch? ;^)
There is a distinction between path and url. A path in unix representation is the location where your particular file or directory exists. Like "/Users/username/Desktop/myfile.txt"
Wheres a url not only contains the location but scheme as well, e.g: http:// or https:// and in our case a file url (file:///Users/username/Desktop/myfile.txt)
Methods like fileExistsAtPath or removeItemAtPath need path in the parameter rather than a url.
While methods like copyItemAtURL:toURL:error:(NSError * _Nullable *)error expects a url.
Use path attribute of NSURL object to retrieve the path. absoluteString gives you the path along with the scheme.

Resources