Search code examples
iphonensstringnsdatansurlwritetofile

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.


Solution

  • 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.