document directory problem? - iphone

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.

Related

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

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.

how to get URL Path for directory inside Document directory?

How can I get url path for a particular directory inside Document Directory.
like Document/Art/
My code
- (NSURL *)localRoot {
if (_localRoot != nil) {
return _localRoot;
}
NSArray * paths = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
_localRoot = [paths objectAtIndex:0];
return _localRoot;
}
The above code is url path for Documents directory but I need Art document directory path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *yourArtPath = [documentsDirectory stringByAppendingPathComponent:#"/Art"];
Use this
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile_a = [documentsDirectory stringByAppendingPathComponent:#"/Art"];
Application.StartupPath;
is used to find your path where your application is being started, if that is what you mean.
Based on above answer here is an simple methode that returns, path for given directory:
+ (NSString *) pathFor : (NSString *) directoryName{
return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:directoryName];
}
You need to implement it in ClassName.m and call as:
NSString *pathForDirectory = [ClassName pathFor:dirName]; //#"Art" in your case

writeToFile path?

I'm wondering what is the default path when saving a file using the NSArray writeToFile:atomically: method...?
[array writeToFile:#"myFile.plist" atomically:YES];
10x
It will save your file at Document directory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = [paths objectAtIndex:0];
this is the path where your file will be saved.
I executed the following code:
if ([#"asdasdasd" writeToFile:#"foo123456.txt" atomically:YES]) {
NSLog(#"+++");
} else {
NSLog(#"---");
}
On the simulator the file foo123456.txt popped up in my root of my HD. The console printed +++, so the operation was successful.
On the device it failed, printing ---.
Use This Code.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
plistpath = [[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:#"Product.plist"]];
And then
[array writeToFile:path atomically:YES];
[Whatever [Array or Dictionary] you want to Write in Plist]
If it is still not creating the plist then check whether your array or dictionary must be empty.

Where To Add File Save Method?

I am saving an array that is editable by the user to the plist. My question is, where in the code to I implement the code? Like one of the methods dealing with the app quitting?
This is the code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"patientList.plist"];
[myPatients writeToFile:path atomically:YES];
I think it depends on how you've implemented your data manager. If you have a singleton to handle accessing / writing data, why not just write data to the file as your singleton array is updated? This way you can be sure data is always saved should something unexpected happen.
What Jordan suggests is definitely one route, but I would use the appWillResign vs willTerminate.
I suggest something like this:
- (void)applicationWillTerminate:(UIApplication *)application
{
[self saveCode];
}
- (void)saveCode
{
SArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"patientList.plist"];
[myPatients writeToFile:path atomically:YES];
}

About 2000 strings to a file

I need to put separate lines into a file, but it seems that it's not supported by
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"myFile"];
[dataString writeToFile:appFile atomically:YES];
It does put a string to a file but it overwrites previous one.
Any suggestions?
To append data to an existing file, create an NSFileHandle instance for that file, then call -seekToEndOfFile and finally -writeData:. You'll have to convert your string into an NSData object yourself (with the correct encoding). And don't forget to close the file handle when you're finished.
The easier, but also less efficient way, is to read the existing file contents into a string, then append the new text to that string and write everything out to disk again. I wouldn't do that in a loop that executes 2000 times, though.
Thanks Ole! That's what I've been looking for.
Some sample code for the others:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//creating a path
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"nameOfAFile"];
//clearing or creating (NSFileHande doesn't support creating a file it seems)
NSString *nothing = #""; //remember it's CLEARING! so get rid of it - if you want keep data
[nothing writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
//creating NSFileHandle and seeking for the end of file
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:appFile];
[fh seekToEndOfFile];
//appending data do the end of file
NSString *dataString = #"All the stuff you want to add to the end of file";
NSData *data = [dataString dataUsingEncoding:NSASCIIStringEncoding];
[fh writeData:data];
//memory and leaks
[fh closeFile];
[fh release];
[dataString release];