Why can't I write files to my app's Document directory? - iphone

I have found several snippets of code describing how to write data to a user's application Documents folder. However, when I try this out in the iPhone simulator, no files get created. I called
[NSFileManager isWritbleAtPath:<my document folder>]
and it returned 0 (false). Do I need to make this folder explicitly writable, and if so, how do I do it?

The iPhone simulator should be able to write to the entire disk. My app routinely dumps test files to the root level of my boot volume (using [NSData's writeToPath:#"/test.jpg" atomically:NO]).
Are you sure that you've correctly determined the path to the documents folder? You need to expand the tilde in the path. Here's the code my app uses to put things in the documents folder. I don't think there's any more setup involved!
brushesDir = [[#"~/Documents/BrushPacks/" stringByExpandingTildeInPath] retain];
// create brush packs folder if it does not exist
if (![[NSFileManager defaultManager] fileExistsAtPath: brushesDir])
[[NSFileManager defaultManager] createDirectoryAtPath:brushesDir withIntermediateDirectories:YES attributes:nil error:nil];

NSLog(#"writable: %d", [[NSFileManager defaultManager] isWritableFileAtPath:NSHomeDirectory()]);
This prints 1 on the console.
Did you mean to call the method isWritableAtPath or isWritableFileAtPath ? And did you mean to call it on the class itself, or on a (default) instance of it?

Thanks for the pointers. So after a toiling through a few documents, I found the thing I was doing wrong: trying to save an NSArray that wasn't composed of basic datatypes such as NSDictionary, NSArray, or NSString. I was trying to save an array of MPMediaItems (from the MediaKit Framework in SDK 3.0+).

I had a trivial issue with the file writing to NSBundle. I had a requirement where a text file needs to be updated with the server as soon as app launches and it worked well with the simulator but not with the device. I later found out that we don't have write permission with NSBundle. Copying the file into Documents directory from NSBundle and using for my purpose solved my problem. I use :
[myPlistData writeToFile:fileName atomically:NO];

Related

iPhone File system operation questions

I want to download files from remote to temp folder
the folder on remote like:
http://remoteserver.com/abc/def/file1.txt
http://remoteserver.com/abc/file2.png
http://remoteserver.com/abc/pla/mnb/file3.html
and the folder structure will like:
tmpefolder/abc/def/file1.txt
tmpefolder/abc/file2.png
tmpefolder/abc/pla/mnb/file3.html
And then after download, will move files to permanent folder like and keep same folder structure
permanentfolder/abc/def/file1.txt
permanentfolder/abc/file2.png
permanentfolder/abc/pla/mnb/file3.html
finally remove all files in tempfolder
So my questions are:
What the best way to download multi files from server? (Better to show ASIHTTPRequest, it is ok to show me other way)
Easy way to create the whole structure of folders? Do I have to split folder path by "/" and check every level path exist and create it?
How to copy whole temp folder content to permanent folder? Is it possible to do this with one operation like copy on OS X?
Also, like remove operation on OS X, remove temp folder with one shot?
Thank you!
1/ You'd better use AFNetwork. ASIHTTPRequest is growing old, no longer maintained. AFNetwork is more modern, and works with blocks (“hmmm, blocks”, like Homer would say). There are plenty of examples around here, just search.
Specifically, AFNetwork allows you to put download operations in a NSOperationQueue, that you can handle at your will, let's say, to download 35 files in parallel, with a maximum of 4 running downloads at the same time, and report to you when everything's done.
2, 3, 4/ Take a look at the reference for NSFileManager. All you need is there.
create .zip of all your file use following code to download .zip form server.
this will create your folder in NSTemporaryDirectory.
NSString *filePath = [NSString stringWithFormat:#"%#/FILENAME.zip",NSTemporaryDirectory()];
[[NSFileManager defaultManager] createFileAtPath:filePath contents:[NSData dataWithContentsOfURL:[NSURL URLWithString:[obj valueForKey:#"zip_path"]]] attributes:nil];
after download move folder to documentDirectory.
[[NSFileManager defaultManager] moveItemAtPath:filePath toPath:[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] error:nil];
following code is remove files form temp
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];

Optimize time access to sqlite using coredata

I'm trying to use a pre-generated sqlite file containing 10 000 objects in a table.
I've created and added objects, with iPhone simulator, in the sqlite using coredata.
I've copy and past the sqlite contained in iPhone Simulator ressource folder (containing 10 000 objects), into my ressource folder in my project directory.
What i do at first launch of my app, is copy this generated database into my app document directory on the iphone using :
NSBundle * mainBundle = [NSBundle mainBundle];
NSString *oldPath = [mainBundle pathForResource:#"MyBase" ofType:#"sqlite"];
NSString *newPath = [[app_delegate applicationDocumentsDirectory] stringByAppendingPathComponent: #"MyBase.sqlite"];
BOOL copied = [[NSFileManager defaultManager] copyItemAtPath:oldPath toPath:newPath error:&error];
if (!copied) {
NSLog(#"Moving database from %# to %#, error: %#", oldPath, newPath, error);
}
It works fine, but i have the following problem :
Comparing access to the original MyBase.sqlite (created on my device and filled with the same 10 000 objects) with the new copy, all access on tables take 3 times more time than on the normal generated MyBase.sqlite.
I wonder if when generating sqlite on simulator, indexed attribute does not exist?
I need help!
Your using a fairly common technique and it does not normally cause any issues. Core Data cannot tell the difference between a store just created and an old one if both stores use the same data model.
The only explanation I can think of is that you are using two different system/API versions such that the store file is subtly different. If the version on device is older/newer than the version on simulator you might have problems.
That's just a wild guess.

using plist in iphone programming

I've read up Apple's documentation of plist: http://developer.apple.com/library/mac/documentation/cocoa/Conceptual/PropertyLists/PropertyLists.pdf
However I've got a few questions about it:
1) When we use the [dict writeToFile:plistPath atomically:YES] API, does it overwrite the current content of the plist? It doesn't say anything in the documentation.
2) Are we supposed to actually make the plist manually in Xcode by new file->resources->property list? Or are we supposed to have this:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSData *xmlData = [NSPropertyListSerialization //... a very long line here
if([fileManager fileExistsAtPath:plistPath]) {
[xmlData writeToFile:plistPath atomically:YES];
}
else {
[fileManager createFileAtPath:plistPath contents:xmlData attributes:nil];
}
3) How do we check if we've actually written data to property list? I tried products -> myapp.app -> "reveal in finder" -> right click -> show package contents, and there are some plists there, but I can't see the data being written! Is that mean I'm failed writing data to plist?
EDIT: Thanks everyone! Sorry for being silly today!
From the description of writeToFile:atomically:
If flag is YES, the dictionary is written to an auxiliary file, and then the auxiliary file is renamed to path. If flag is NO, the dictionary is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.
Since it is written to an auxiliary file and then renamed to the specified path, I would assume that it overwrites the current content of the file.
You should use the NSFileManager to find the application's documents directory and write the plist there. You should not use a resource, as you are going to write to it during the course of executing the app.
Add some logging (e.g., NSLog(#"plist path: %#", plistPath);) to show where the plist is getting written.
1) It will overwrite the current content. If you want to append some more data to your current plist file, first read it to a dictionary and add the data and write it back.
2) You can add it manually or create it programmatically.
3) Just log the contents of the plist file after writing.

NSFileManager - Copying Files at Startup

I need to copy a few sample files from my app's resource folder and place them in my app's document folder. I came up with the attached code, it compiles fine but it doesn't work. All the directories I refer to do exist. I'm not quite sure what I am doing wrong, could someone point me in the right direction please?
NSFileManager*manager = [NSFileManager defaultManager];
NSString*dirToCopyTo = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString*path = [[NSBundle mainBundle] resourcePath];
NSString*dirToCopyFrom = [path stringByAppendingPathComponent:#"Samples"];
NSError*error;
NSArray*files = [manager contentsOfDirectoryAtPath:dirToCopyFrom error:nil];
for (NSString *file in files)
{
[manager copyItemAtPath:[dirToCopyFrom stringByAppendingPathComponent:file] toPath:dirToCopyTo error:&error];
if (error)
{
NSLog(#"%#",[error localizedDescription]);
}
}
EDIT: I just edited the code the way it should be. Now however there's another problem:
2010-05-15 13:31:31.787 WriteIt
Mobile[4587:207] DAMutableDictionary.h
2010-05-15 13:31:31.795 WriteIt
Mobile[4587:207] FileManager
Error:Operation could not be
completed. File exists
EDIT : I have fixed the issue by telling NSFileManager the names of the copied files's destinations.
[manager copyItemAtPath:[dirToCopyFrom stringByAppendingPathComponent:file] toPath:[dirToCopyTo stringByAppendingPathComponent:file] error:&error];
I think the problem is in this line:
NSArray*files = [manager contentsOfDirectoryAtPath:dirToCopyTo error:nil];
You are listing files in a destination directory instead of the source. Change it to something like:
NSArray*files = [manager contentsOfDirectoryAtPath:dirToCopyFrom error:nil];
And you should be fine.
I think the problem is that yo are reading the files to copy from dirToCopyTo and I think you meant dirToCopyFrom
Also to get the documents directory you should be using NSDocumentDirectory with - (NSArray *)URLsForDirectory:(NSSearchPathDirectory)directory inDomains:(NSSearchPathDomainMask)domainMask
Please note that lengthy operation on startup must be avoided:
Not a good User Experience (delay and croppy behavior)
Watchdog in iOS can kill your app as if it were stuck.
So perform copy in a secondary thread (or operation... or whatever uses a different execution path).
Another problem will arise if You need data to populate your UI: in that case:
Disable UI elements
Start an async / threaded operation
In the completion call back of copying (via a notification, a protocol.. or other means)
notify to the UI interface it can start fetching data.
For example we copy a ZIP file and decompress it, but it takes some time so we had to put it in a timer procedure that will trigger UI when done.
If You need an example, ket me know.
PS:
Copying using ZIP file is MORE efficient as:
Only call to file system
Far less bytes to copy
The bad news: you must use a routine do decompress zip file, but you can find them on the web.
Decompressing Zip files should be more efficient as these calls are written in straight C, and not in Cocoa with all the overhead.
[manager copyItemAtPath:[dirToCopyFrom stringByAppendingPathComponent:file] toPath:dirToCopyTo error:&error];
The destination path is the path you want the copy to have, including its filename. You cannot pass the path to a directory expecting NSFileManager to fill in the name of the source file; it will not do this.
The documentation says that the destination path must not describe anything that exists:
… dstPath must not exist prior to the operation.
In your case, it's the path to the destination directory, so it does exist, which is why the copy fails.
You need to make it a path to the destination file by appending the desired filename to it. Then it will not exist (if not previously copied), so the copy will succeed.

Find all files in iphone project

I'm curious if there's a way to search for files in the iPhone's directory ( the location is irrelevant).
I am wanting to load in addresses from text files. The thing is additional files may be added and I want to dynamically be able to find the files and load in the data without hardcoding the file names to load in.
Thanks a bunch!
You want:
NSError *error;
[[NSFileManager defaultManager] contentsOfDirectoryAtPath:myPath error:&error]
It returns an array of NSString objects for each file in the given directory.