Reading file's content downloaded from dropbox -objective-c - iphone

I want to read and print the file's content which downloaded from dropbox but my "readFile" method prints null. I am sure the file is downloaded successfully.
-(void)download
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", #"File.txt"]];
[[self restClient] loadFile:#"/File.txt" intoPath:filePath];
}
- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
contentType:(NSString*)contentType metadata:(DBMetadata*)metadata {
[self readFile:#"File.txt"];
NSLog(#"File loaded into path: %#", localPath);
}
-(void)readFile:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileNameData=[NSString stringWithFormat:#"%#",fileName];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileNameData];
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSError *error;
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", error);
}
and this is output:
---------******** CONTENT OF THE DOWNLOADED FILE *********------------(null)
I updated my code for capture erorr and I am getting this error from stringWithContentsOfFile:
Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)" UserInfo=0x1669c2b0 {NSFilePath=/var/mobile/Applications/11B10727-E372-1147-26BD-1D24S60B8E54/Docume‌​nts/File.txt, NSStringEncoding=4} 2013-08-05 22:06:03.229 DBApp[496:60b]

It looks like your code is reading a file called "File.txt" rather than the actual file that was downloaded from Dropbox. Am I missing something?
EDIT
Based on the comments below, it looks like the error is 261, related to string encoding. You might want to try a different encoding or ensure that the text file is encoded the way you expect it to be.

Related

Error while writing data to a file in iphone

in my application, i have placed an empty
myFile.txt
when i have internet connection , i get json data from internet and save the json string in it with following code
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"myFile" ofType:#"txt"];
[myString writeToFile:filePath automatically:YES encoding:NSUTF... error:nil];
//now while retrieving it when no internet connection
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"myFile" ofType:#"txt"];
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF.. error:nil];
now myString returns with #""... why i am not been able to write data?
Best Regards
Whatever you want to do is not possible (or at least strongly discouraged) to update files in the app bundle.
If you’re downloading files and want to store them on the device you should use the Documents directory. You can get the path to this directory with:
- (NSString *)getDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
First check weather the contents are getting written to file. You can view the file in xcode.
What i suggest is when you run the app create this empty file. Then you can Read and write to that file easily.
Try Using Below code:
NSError* error = nil;
NSString* jsonFileName = [NSString stringWithFormat:#"myfile"];
NSString* jsonPath = [[NSBundle mainBundle] pathForResource:jsonFileName
ofType:#"txt"];
NSString* jsonString = [NSString stringWithContentsOfFile:jsonPath
encoding:NSUTF8StringEncoding error:&error];
Documents directory:
Write to file
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = #"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
Display content:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];

Create and save NSString data in to a file

i have 3NSString objects that i want to save to a new file when the app is running.
this will help me for remote debug!
if any one can help me creating the file and save the data to it will be very use full
thanx
You can save the files to the Documents directory, here is how to get the path to that directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
And a sample write statement:
NSError *error;
BOOL status = [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
In the NSString documentation there is method called writeToFile:atomically:encoding:error:.
NSError *error;
[#"Write me to file" writeToFile:#"<filepath>" atomically:YES encoding: NSUTF8StringEncoding error:&error];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error; BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:#"myfile.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
// Handle error here }
source.
Here is how to save NSString into Documents folder. Saving other types of data can be also realized that way.
- (void)saveString:(NSString *)stringToSave toDocumentsWithFilename:(NSString *)fileName {
NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *path = [documentsFolder stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}
Usage:
NSString *stringWeWantToSave = #"This is an elephant";
NSString *fileName = [NSString stringWithString:#"savedString.txt"];
[self saveString:stringWeWantToSave toDocumentsWithFilename:fileName];

string is not being written in file - iPhone

I am using the following code in iPhone to write a string into the file that is stored in my iPhone Project Resource Folder. When i try to read its reading the data successfully but when i try to write its not writing the file although its aloso not giving me any error.
this is my code:
NSString *myString; //Assuume the string you want to write is this
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"myfile.txt"];
[myString writeToFile:path atomically:YES];
Please can anybody guide.
- (void) testStringReadWrite {
NSString *myString = #"abcd efgh";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"myfile.txt"];
CFShow(path);
NSError *error = nil;
[myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%#",error);
}
NSString *readString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%#", error);
} else {
CFShow(readString);
}
}
The writeToFile:atomically: has been depredecated in iOS 2.0. Use writeToFile:atomically:encoding:error: instead. You should check the content of the string, for example by NSLog() function. Inappropriate initialization can cause a failure.
NSLog(#"%#", myString);
[myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
Just my two cents, coming from OS X, I am used to calling writeToURL() instead of writeToFile(). Turns out, writeToFile() is the one that worked for iOS.

Read/write file in Documents directory problem

I am trying to write a very basic text string to my documents directory and work from there to later save other files etc.
I am currently stuck with it not writing anything into my Documents directory
(In my viewDidLoad)
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
NSString *documentsDirectory = [pathArray objectAtIndex:0];
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:#"file1.txt"];
NSString *text = #"My cool text message";
[[NSFileManager defaultManager] createFileAtPath:textPath contents:nil attributes:nil];
[text writeToFile:textPath atomically:NO encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"Text file data: %#",[[NSFileManager defaultManager] contentsAtPath:textPath]);
This is what gets printed out:
2011-06-27 19:04:43.485 MyApp[5731:707] Text file data: (null)
If I try this, it also prints out null:
NSLog(#"My Documents: %#", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:NULL]);
What have I missed or am I doing wrong while writing to this file?
Might it be something I need to change in my plist or some frameworks/imports needed?
Thanks
[EDIT]
I passed a NSError object through the writeToFile and got this error:
Error: Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x12aa00 {NSFilePath=/var/mobile/Applications/887F4691-3B75-448F-9384-31EBF4E3B63E/Documents/file1.txt, NSUnderlyingError=0x14f6b0 "The operation couldn’t be completed. Not a directory"}
[EDIT 2]
This works fine on the simulator but not on my phone :/
Instead of using NSFileManager to get the contents of that file, try using NSString as such:
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
NSString *documentsDirectory = [pathArray objectAtIndex:0];
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:#"file1.txt"];
NSError *error = nil;
NSString *str = [NSString stringWithContentsOfFile:textPath encoding:NSUTF8StringEncoding error:&error];
if (error != nil) {
NSLog(#"There was an error: %#", [error description]);
} else {
NSLog(#"Text file data: %#", str);
}
Edit: Added error checking code.
How are you getting documentsDirectory?
You should be using something like this:
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
NSString *documentsDirectory = [pathArray lastObject];
Put an NSLog statement after every line where you are setting a variable's value, so that you can inspect those values. This should help you quickly pinpoint where things start to go wrong.
The problem got solved by setting a non standard Bundle ID in die info.plist
I used the Bundle ID from iTunes Connect for this specific app. Now everything works perfectly.
You can also use NSFileHandle for writing data in file and save to document directory:
Create a variable of NSFileHandle
NSFileHandle *outputFileHandle;
use the prepareDataWrittenHandle function with passing file name in parameter with file extension
-(void)prepareDataWrittenHandle:(NSString *)filename
{
//Create Path of file in document directory.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *outputFilePath = [documentsDirectory stringByAppendingPathComponent:filename];
//Check file with above name is already exits or not.
if ([[NSFileManager defaultManager] fileExistsAtPath:outputFilePath] == NO) {
NSLog(#"Create the new file at outputFilePath: %#", outputFilePath);
//Create file at path.
BOOL suc = [[NSFileManager defaultManager] createFileAtPath:outputFilePath
contents:nil
attributes:nil];
NSLog(#"Create file successful?: %u", suc);
}
outputFileHandle = [NSFileHandle fileHandleForWritingAtPath:outputFilePath];
}
then write the string value to file as:
//Create a file
[self prepareDataWrittenHandle:#"file1.txt"];
//String to save in file
NSString *text = #"My cool text message";
//Convert NSString to NSData to save data in file.
NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding]
//Write NSData to file
[_outputFileHandle writeData:data];
//close the file if written complete
[_outputFileHandle closeFile];
at the end of file written you should close the file.
You can also check the content written in file as NSString for debug point of view as mention above by #Glenn Smith:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *outputFilePath = [documentsDirectory stringByAppendingPathComponent:#"file1.txt"];
NSError *error;
NSString *str = [NSString stringWithContentsOfFile:outputFilePath encoding:NSUTF8StringEncoding error:&error];
if (error != nil) {
NSLog(#"There was an error: %#", [error description]);
} else {
NSLog(#"Text file data: %#", str);
}

document directory problem?

When i write Data(53MB ) to Document directory ,the data is not written when i check directly through application support path.i coded like this,
- (BOOL)writeApplicationData:(NSData *)data toFile:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
return NO;
}
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
return ([data writeToFile:appFile atomically:YES]);
}
it works fine, but when i read the data using follwing code, the data is null, anyhelp pls?
- (NSData *)applicationDataFromFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease];
return myData;
}
The code is working for me (on a small download).
Some thoughts, are you downloading the 53MB over the network? Perhaps you're trying to read it before it's finished? The "atomically" flag on write to file says:
If YES, the data is written to a backup file, and then—assuming no errors occur—the backup file is renamed to the name specified by path; otherwise, the data is written directly to path.
If you're downloading this Asynchronously and can't use partial results, you may have to wait for it to complete. Otherwise you can set the atomically:NO and read in the partial result.