How to copy a file from a URL to a document folder?

I need to copy a text file from a URL and put / rewrite it in the application document folder, and then read it back into the 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 executes in a good way, but I can’t create the text.txt file in the folder of my document and then pass anything into my data variable. I am new to iOS and Xcode, any hints would be much appreciated. Thanks!!

+4
source share
2 answers

NSFileManager can only handle local paths. It will not be useful if you provide a URL.

copyItemAtPath:toPath:error:accepts an error parameter. Use it for example:

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

You would 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"}

http://www.abc.com/text.txt, .


Sunny Shah , URL-:

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.");
        }
    }
}

!

+2

URL- WriteToFile

 NSData *urlData = [NSData dataWithContentsOfURL: [NSURL URLWithString:urlText]];
    [urlData writeToFile:filePath atomically:YES];
+1

Source: https://habr.com/ru/post/1525748/


All Articles