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!!
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With