Objective-C / Can't access (read) file in "Resources" folder - objective-c

This is probably a very easy problem to solve but i have not succeeded. I have copied the file "questions_famquiz_easy_110326.txt" to the resources folder and now want to access (read) it and NSLog it to see that i am able to read it.
The code below is from one of the tests i have done based on examples that i have found on the web.
I am trying to access a txt-file in the Resources folder and fail to do so. I have searched for a solution, tested a lot, but not succeeded.
I am testing with the following code:
NSLog(#"\n \n >>>>>>viewDidLoad<<<<<<<<<");
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsDirectory stringByAppendingPathComponent:#"questions_famquiz_easy_110326.txt"];
if(![fileManager fileExistsAtPath:filePath])
{
NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:#"/questions_famquiz_easy_110326.txt"]];
[data writeToFile:filePath atomically:YES];
}
NSString *myString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"myString: %#", myString);
NSLog(#"\n \n>>>>>>DONE WITH viewDidLoad<<<<<<<<<");
exit(0); //====EXIT JUST FOR THE TEST====<<<
The above code is located in the first viewController that is started.
The output i get is:
>>>>>>viewDidLoad<<<<<<<<<
2011-04-24 21:53:47.825 FamQuiz_R0_1[542:307] myString: (null)
2011-04-24 21:53:51.044 FamQuiz_R0_1[542:307]
>>>>>>DONE WITH viewDidLoad<<<<<<<<<
Could someone nice help me to solve this?
update:
Here is the filePath:
2011-04-24 22:38:08.562 FamQuiz_R0_1[637:307] filePath: /var/mobile/Applications/7F5FDB03-0D22-46BC-91BC-4D268EB4BBEB/FamQuiz_R0_1.app/questions_famquiz_easy_110326.txt
Here is where i have placed the file:
PROBLEM SOLVED:
NSString *myString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
When i used the above it did not work, when i used the below it worked and printed out the text.
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath];

You're not reading from the resources folder. You're trying to read from the document directory. So getting back nil makes sense since the file doesn't exist there.
Change:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsDirectory stringByAppendingPathComponent:#"questions_famquiz_easy_110326.txt"];
to:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"questions_famquiz_easy_110326" ofType:#"txt"];
and it should work for you.

Related

How to save and retrieve files to apps temp folder in ios

I'm new to IOS development. I'm developing an app which involves downloading files and saving that to apps temp folder and I dont know how to do that my current code is given below
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSLog(#"%#",tmpDirURL);
NSString *myString = [tmpDirURL absoluteString];
for(int i=0;i<responseArray.count;i++){
ASIHTTPRequest *saveUrl = [ASIHTTPRequest requestWithURL:responseArray[i]];
[saveUrl setDownloadDestinationPath:myString];
[request startSynchronous];
}
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:myString error:&error];
NSLog(#"%#",directoryContents);
The response array contain a list of URL for downloading files. I know something wrong with my code but I cant find out that error please help me to solve this problem
I found the solution'
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *htmlFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
[data writeToFile:htmlFilePath atomically:YES];
When downloadDestinationPath is set, the result of this request will be downloaded to the file at this location. If downloadDestinationPath is not set, download data will be stored in memory
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSLog(#"%#",tmpDirURL);
NSString *myString = [tmpDirURL absoluteString];
for(int i=0;i<responseArray.count;i++){
ASIHTTPRequest *saveUrl = [ASIHTTPRequest requestWithURL:responseArray[i]];
[saveUrl setDownloadDestinationPath:[myString stringByAppendingPathComponent:[NSString stringWithFormat:#"%i",i ]]; // for each file set a new location inside tmp
[request startSynchronous];
}
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:myString error:&error];
NSLog(#"%#",directoryContents);

Error writing to plist in documents directory

I use the following code to copy a Resources plist file into the documents directory:
BOOL success;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Test-Info.plist"];
success = [fileManager fileExistsAtPath:filePath];
if (!success) {
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:#"Test-Info.plist"];
success = [fileManager copyItemAtPath:path toPath:filePath error:&error];
NSLog(#"Test-Info.plist successfully copied to DocumentsDirectory.");
}
I get the success message, which is great. I'm assuming it's been copied correctly into the documents folder.
However when I then try to read and write to the saved plist file it returns null:
Key entry in Test-Info.plist:
Key: EnableEverything
Type: Boolean
Value: YES
Write code:
NSString *adKey = #"EnableEverything";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:#"Test-Info.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
NSString *enableEverything = [[plist valueForKey:adKey] stringValue];
NSLog(#"****** EXISTING: %# ******", enableEverything); // returns (null)
// Disable in plist.
[plist setValue:0 forKey:adKey]; // will this work?
[plist writeToFile:path atomically:YES]; // this doesn't throw an error?
NSString *enableEverything1 = [[plist valueForKey:adKey] stringValue];
NSLog(#"****** NOW: %# ******", enableEverything1); // returns (null)
Output:
****** EXISTING: (null) ******
****** NOW: (null) ******
My question is why are they (null) when they exist within the plist file?
You are trying to mutate an immutable object.
You need a NSMutableDictionary.
IE
NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile: path] mutableCopy];
Also check, if the plist object isnt nil, as any messages can be send to nil without raiing an error. this wouldnt fail, also nothing actually happens.
[plist setValue:0 forKey:adKey]; // will this work?
[plist writeToFile:path atomically:YES]; // this doesn't throw an error?
as the source path is nil, you are most like not copying the file during compilation bundling. drag it here:
Try this for nsbundle path for resource
NSString *path= [[NSBundle mainBundle] pathForResource:#"SportsLogo-Info" ofType:#"plist"];
Try allocating
NSMutableDictionary *plist = [[NSMutableDictionary alloc] initWithDictionary:[NSDictionary dictionaryWithContentsOfFile:path]];
Also check if the file has been copied or not. Go to Library=>Application Support=>iPhone Simulator=>folder named your version of simulator iOS=>Applications=>Find the right folder of your project=>Documents see if the plist file is there

Copy file to App Document folder automatically

I want to copy set of files from project resource folder to the app document folder automatically at the time of app first launch. Can I do this. Do I need to do it through the code.
BOOL success;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Data.txt"];
success = [fileManager fileExistsAtPath:filePath];
if (!success) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"txt"];
success = [fileManager copyItemAtPath:path toPath:filePath error:&error];
}
In application did finish launching with options

copy all files with extension to documents directory

I am having a little bit trouble with copying files from an online place to the Documents Directory of the iPad in xcode.
The files that i want to download had to be the files with the extension 'xml'.
now i am doing this:
NSData *onlineLink = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://localhost:8888/"]];
NSString *extension = #"xml";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:onlineLink error:NULL];
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;
while ((filename = [e nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[fileManager copyItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename toPath:documentsDirectory error:NULL]];
}
}
However this does not work, i get this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteData fileSystemRepresentation]: unrecognized selector sent to instance 0xb000800'
Can anybody give me a hint why i am getting the error?
in the line:
NSArray *contents = [fileManager contentsOfDirectoryAtPath:onlineLink error:NULL];
contentsOfDirectoryAtPath should be an NSString, you are passing an NSData object

Copying plist file to custom folder in ApplicationSupport (Objective-C)

I have this piece of code, which copies a plist file to the ApplicationSupport directory in the users folder.
NSString *resourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kAutonumberPlist];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *dataPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:kAutonumberPlist];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:dataPath]) {
[fileManager copyItemAtPath:resourcePath toPath:dataPath error:nil];
}
How ca I change it so that instead of copying the file into ~User/Library/ApplicationSupport, it will copy it into ~User/Library/ApplicationSupport/AnotherFolder. The "AnotherFolder" already exists by the way.
Thank you!
You are already using stringByAppendingPathComponent - you could just use it again.
For example:
NSString *dataPath = [[[paths objectAtIndex:0]
stringByAppendingPathComponent: #"AnotherFolder"]
stringByAppendingPathComponent: kAutonumberPlist];