Check if file is already saved to disk? - iphone

I am downloading files from my server, saving them to device, and displaying them to the user in my app. I want to implement a check to see if the file already exists on the device so we can skip the download and just display, but I can't figure out the best way to do that.
I create a unique fileName for each file and then convert it to an NSURL like this:
NSString *fileString = [[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:fileName]];
self.fileURL = [[NSURL alloc] initFileURLWithPath:fileString];
Then I write to file and save the URL for use shortly after:
[data writeToFile:fileString atomically:YES];
self.fileURL = [[NSURL alloc] initFileURLWithPath:fileString];
How can I check if that File or URL already exists?
Thanks

NSFileManager has a method to check if a file exists at a path:
[[NSFileManager defaultManager] fileExistsAtPath: fileString]
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsfilemanager_Class/Reference/Reference.html#//apple_ref/doc/uid/20000305-CHDDDDJG

Related

FileExistsAtPath returning NO on movie from UIImagePickerController

I saved a movie file's path from UIImagePickerController, and I know it exists because I can play it on the device. An NSLog on the string containing the movie file path returns this:
file://localhost/private/var/mobile/Applications/E694555D-3959-4CC5-A829-4260323C2C65/tmp//trim.6JemAI.MOV
When this string is used like this however, it returns NO:
NSLog(#"file exists: %i", [[NSFileManager defaultManager] fileExistsAtPath:media.movie]);
Any idea this this is failing? Could it be related to the value being stored as a path, or perhaps that the path includes // at one point? These are just some thoughts I've had.
You need to convert the URL to a file path.
NSURL *url = info[UIImagePickerControllerMediaURL];
NSString *path = [url path];
NSLog(#"file exists: %i", [[NSFileManager defaultManager] fileExistsAtPath:path]);
A path doesn't have the leading file://localhost.

How can I get relative path of the folder in my project ?(iPhone)

Suppose, I have added one folder name "Images" in my project.How can I get the path to that folder? My main intention is to get the number of pictures in "Images" folder.
You should work a bit more on your question: it assumes a lot and requires the reader to guess.
I have added one folder name "Images" in my project
So I guess this means you added it as a folder reference
and I want to get it's path
And I guess that you want to do that at run time from your application, not at build-time from Xcode.
If so, you could do something like:
NSURL *containingURL = [[NSBundle mainBundle] resourceURL];
NSURL *imageURL = [containingURL URLByAppendingPathComponent:#"Images" isDirectory:YES];
NSFileManager *localFileManager = [[NSFileManager alloc] init];
NSArray *content = [localFileManager contentsOfDirectoryAtURL:imageURL includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsSubdirectoryDescendants error:NULL];
[localFileManager release];
NSUInteger imageCount = [content count];
This code does not assume that all images are of the same kind.
[[[NSBundle mainBundle] pathsForResourcesOfType:#"jpg" inDirectory:#"Images"] count];
This returns the number of jpg images from the Images folder. This is the case if you added the images to your application bundle.

Store and Load File from URL

iPhone App
I am currently trying to understand how i can store a file from a URL to the documents directory and then read the file from the documents directory..
NSURL *url = [NSURL URLWithString:#"http://some.website.com/file"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:#"Timetable.ics"];
[data writeToFile:storePath atomically:TRUE];
I got this code from http://swatiardeshna.blogspot.com/2010/06/how-to-save-file-to-iphone-documents.html
I want to know if this is the correct way to do this and i want to know how i can load the file from the documents directory into an NSString..
Any help will be greatly appreciated.
What you have looks correct, to read that file back into a string use:
EDIT: (changed usedEncoding to encoding)
NSError *error = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:storePath encoding:NSUTF8StringEncoding error:&error];
Of course you should change the string encoding type if you are using a specific encoding type, but UTF8 is likely correct.
If you're doing this on your main thread, then no it's not correct. Any sort of network connection should be done in the background so you don't lock up the interface. For that, you can create a new thread (NSThread, performSelectorInBackground:, NSOperation+NSOperationQueue) or schedule it on the run loop (NSURLConnection).

ASIHTTP asynchrounous pdf download

Can anyone please provide or show me how to download a PDF asynchronously if a local file doesnt exist.
My code is as follows:
NSURL *url = [NSURL URLWithString:#"http://www.url.com"];
NSString *tempDownloadPath = [[self documentsDirectory]
stringByAppendingString:#"test.pdf"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:[self documentsDirectory]];
[request setTemporaryFileDownloadPath:tempDownloadPath];
[request setDelegate:self];
[request startAsynchronous];
Once it is complete I try and call this
[aWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[self documentsDirectory] pathForResource:#"test" ofType:#"pdf"]isDirectory:NO]]];
however it either crashes or doesn't load anything inside my web view.
Any suggestions?
EDIT WITH SELF DOCUMENTSDIRECTORY
You need to put your file in some place accessible to the UIWebView and then point it there. You've not included how you're creating [self documentsDirectory] and you're just appending a string rather than using the path append for your temporary location. You're also not telling ASIHTTPRequest what actual file name to use for the final document, just the directory to put it in, so it's likely not even being saved. Additionally, the UIWebView load request is incorrect.
Here's how to create your path for telling ASIHTTPRequest where to put the file.
EDITED to change temporary file location to the NSCachesDirectory instead, so that it will be automatically cleared out if the download fails with partial data
// SAVED PDF PATH
// Get the Document directory
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// Add your filename to the directory to create your saved pdf location
NSString *pdfLocation = [documentDirectory stringByAppendingPathComponent:#"test.pdf"];
// TEMPORARY PDF PATH
// Get the Caches directory
NSString *cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// Add your filename to the directory to create your temp pdf location
NSString *tempPdfLocation = [cachesDirectory stringByAppendingPathComponent:#"test.pdf"];
// Tell ASIHTTPRequest where to save things:
[request setTemporaryFileDownloadPath:tempPdfLocation];
[request setDownloadDestinationPath:pdfLocation];
Then when your delegate receives notification of the file download being complete, tell the UIWebView where to find the file, again using the proper methods.
// If you've stored documentDirectory or pdfLocation somewhere you won't need one or both of these lines
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *pdfLocation = [documentDirectory stringByAppendingPathComponent:#"test.pdf"];
// Now tell your UIWebView to load that file
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:pdfLocation]]];
I think the error is that you're downloading the file to the documents directory and then you're looking for the file in the main bundle. You should look for it in the documents directory.

How to get an NSarray of all file names in a directory on a remote server?

How do I get an NSArray of the NAMES of all files stored in a specific directory such as: "http://www.someurl/somedirectory/"?
That's really something that has to be generated server-side, then parsed on the device. I know Apache has an option where you can turn on Directory Indexes, so you could do that, then download the generated directory index and parse the HTML (using an NSXMLParser or some other parsing library), adding an NSString to an NSMutableArray every time you find a file name.
Should be something along these lines..
NSURL* url = [NSURL URLWithString: #"http://address.tld/path/files.txt"];
NSString* data = [NSString stringWithContentsOfURL: url];
if(data)
{
NSArray* files = [data componentsSeparatedByString: #"\n"];
for(NSString* filename in files)
{
NSLog(#"%#", filename);
}
}