Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a file from URL to document folder?

I need to copy a text file from an URL and place / overwrite it in my app's document folder and then read it back to a data variable. I have the following code:

NSData *data;

//get docsDir
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir=[paths objectAtIndex:0];

//get path to text.txt
NSString *filePath=[docsDir stringByAppendingPathComponent:@"text.txt"];

//copy file
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;

if([fileManager fileExistsAtPath:filePath]==YES){
    [fileManager removeItemAtPath:filePath error:&error];
}

NSString *urlText = @"http://www.abc.com/text.txt";

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    [fileManager copyItemAtPath:urlText toPath:filePath error:NULL];
}

//Load from file
NSString *myString=[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

//convert string to data
data=[myString dataUsingEncoding:NSUTF8StringEncoding];

It builds and complies in good way but I cannot create the text.txt file in my document folder and then pass anything to my data variable. I'm a newbie to both IOS and Xcode, any clues will be highly appreciated. Thanks!!

like image 368
Tallent Siu Avatar asked Oct 21 '22 15:10

Tallent Siu


1 Answers

NSFileManager can only handle local paths. It won't do anything useful if you give it a URL.

copyItemAtPath:toPath:error: takes an error parameter. Use it, like this:

NSError *error;
if (![fileManager copyItemAtPath:urlText toPath:filePath error:&error]) {
    NSLog(@"Error %@", error);
}

You would then get this error:

Error Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be
completed. (Cocoa error 260.)" UserInfo=0x9a83c00 {NSFilePath=http://www.abc.com/text.txt, 
NSUnderlyingError=0x9a83b80 "The operation couldn’t be completed. 
No such file or directory"}

It can't read the file at http://www.abc.com/text.txt, because it is not a valid path.


as Sunny Shah stated without explanation you have to fetch the object at the URL first:

NSString *urlText = @"http://www.abc.com/text.txt";

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
    NSURL *url = [NSURL URLWithString:urlText];
    NSError *error;
    NSData *data = [[NSData alloc] initWithContentsOfURL:url options:0 error:&error];
    if (!data) { // check if download has failed
        NSLog(@"Error fetching file %@", error);
    }
    else {
        // successful download
        if (![data writeToFile:filePath options:NSDataWritingAtomic error:&error]) { // check if writing failed
            NSLog(@"Error writing file %@", error);
        }
        else {
            NSLog(@"File saved.");
        }
    }
}

Always check for errors!

like image 108
Matthias Bauch Avatar answered Oct 24 '22 11:10

Matthias Bauch