I am building a simple iOS app. And I need to read some data from a text file.
But I don't know where to put it.
I have tried to put it under the Debug-iphoneos or Debug-iphonesimulator. But it doesn't work.
Drag it into your project. When asked if it should be part of the app target, make sure it is. The result is that when you build the app, the file will be copied into the app bundle and thus will make its way onto the target device as part of the app, where your code can retrieve it, along these lines:
NSString* f = [[NSBundle mainBundle] pathForResource:#"myfile" ofType:#"txt"];
NSError* err = nil;
NSString* s = [NSString stringWithContentsOfFile:f
encoding:NSUTF8StringEncoding
error:&err];
The main bundle should work like others have stated, if you want to access it for testing via the documents directory for some testing or other purposes. This should give you the directory for that app:
NSLog(#"%#",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] objectAtIndex:0]);
Resulting URL for if you decide to put it into the documents folder:
[[[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] objectAtIndex:0]URLByAppendingPathComponent:#"YOUR_FILE_NAME_HERE"] URLByAppendingPathExtension:#"txt"];
Related
I'm trying to access a resource file I added in the app using relative pathing. I've read that I was supposed to use something like this :
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [[mainBundle resourcePath] stringByAppendingPathComponent:#"myFile.txt"];
fh = [NSFileHandle fileHandleForReadingAtPath:resourcePath];
Except this isn't working. With NSLog, I am able to confirm mainBundle isn't null and resourcePath returns something like this:
/Users/tom/Library/Developer/CoreSimulator/Devices/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX/data/Containers/Bundle/Application/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX/MyApp_Demo.app/myFile.txt
I've tried many things, such as adding the name of directory where the resource is located, that would be Ressources/myFile, but nothing is yielding any result.
I'm a total beginner with Objective-C but I have to tinker with legacy code and I have to deal with this, so any help is much appreciated.
Side note:
this is what the project structure looks like from Xcode:
Meanwhile, in Finder, the Ressources directory isn't inside the MyApp directory, rather they're on the same level inside the project directory. I wonder if that could be the problem.
Side note 2:
NSString *filePath2 = [[NSBundle mainBundle] pathForResource:#"myFile" ofType:#"txt"];
returns (null) after logging in the console.
It is best to use a simulator for this debugging process
Verification
You should check if the file or Resources folder is actually being copied to the right location or not. If you have added the Resources folder, than check it with the below code
NSString *resourcesFolderPath = [[NSBundle mainBundle] pathForResource:#"Resources" ofType:nil];
NSString *fullFilePath = [NSString pathWithComponents:#[demoToursPath,"filename.txt"]];
NSFileManager *manager=[NSFileManager defaultManager];
NSLog(#"Filepath: %#", fullFilePath);
NSLog(#"File Exist: %#", [manager fileExistsAtPath:fullFilePath]);
Once you have confirmed this, you can update your code to match the location and path it needs to be in order to access the file.
Additional Debug
You can also just print the Document Directory for the application and open a finder window and navigate there to see if the Resources folder is added at the right place (if it was added)
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]
NSLog(#"Document Directory: %#", documentDir);
If you update the question with more info, I would be able to help you better
After I build an app with sqlite. I have installed SQLite manager in Firefox. Doesn´t help because I really don´t know where is that file. I tried many ways.
And finally I try to find this file
_databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"myUsers.db"]];
To open with MesaSQLite
Still have the same problem. Where is my file.
Here is the last way I have used:
/Users/{YOUR NAME}/Library/Developer/CoreSimulator/Devices/{DEVICE ID}/data/Containers/Data/Application/{APPLICATION ID}/
I still can not find it. I have open almost every project folders.
Please help me.
Dont open Library on MacintoshHDD. You need to open Library on your USERName Folder. There,normally library folder is hidden. You need to follow the following to see the hidden files.
Or simply copy paste the path into the search finder on your mac.It will take you directly.
The long way to show hidden Mac OS X files is as follows:
Open Terminal found in Finder > Applications > Utilities.
In Terminal, paste the following:
defaults write com.apple.finder AppleShowAllFiles YES.
Press return.
Hold 'alt' on your keyboard, then right click on the Finder icon in the dock and click Relaunch.
You should be able to find this using this method :
- (NSURL *)applicationDocumentsDirectory
{
NSLog(#"%#",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
Just copy paste whatever is logged in navigate into the folder where you stored your sqlite file
The end result should look like this :
~/Library/Developer/CoreSimulator/Devices/4D2D127A-7103-41B2-872B-2DB891B978A2/data/Containers/Data/Application/0323215C-2B91-47F7-BE81-EB24B4DA7339/Documents/MyApp.sqlite
Please note that the long ID's will obviously be different, as well as the file name.
You just following line of code to Log.
NSString *databasePath = [[NSBundle mainBundle] pathForResource:#"myUsers" ofType:#"db"];
Or use below code.
NSBundle* bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:#"myUsers" ofType:#"bundle"]];
NSLog(#"%#", bundle);
NSString* test = [bundle pathForResource:#"myUsers" ofType:#"db"];
NSLog(#"%#", test);
NSDictionary* dict = [NSDictionary dictionaryWithContentsOfFile:[bundle pathForResource:#"Root" ofType:#"plist"]];
NSLog(#"%#", dict);
I am using the Core Data Editor a lot for my iOS projects. It is compatible with Mac and iOS applications and support XML, SQLite and binary stores, etc. It is free. :-)
http://thermal-core.com/CoreDataEditor/
This question already has answers here:
Does an iOS app have write access inside its bundle?
(2 answers)
Closed 8 years ago.
beg-counter.txt file is already in my application's bundle....now i wanted to write into it...but i can't....
i can read that file but not able to write into it....
here is my code.......
value of level_beg_cnt is suppose 2.
NSError *error;
NSString *Path = [[NSBundle mainBundle] pathForResource:#"beg_counter" ofType:#"txt"];
NSLog(#"string to write:%#",level_cnt_beg);
[level_cnt_beg writeToFile:Path atomically:YES
encoding:NSUTF8StringEncoding error:&error];
The bundle is read-only. You don't want to mess around with it for two reasons:
Code Signing: the signature is verified by against the contents of the bundle; if you mess around with the bundle, you break the signature.
App Updates: updates work by replacing the entire app bundle with a newly downloaded one; any changes you make will get lost.
Where you should save stuff:
Documents: if you want it to persist and be backed up
Library/Caches: if you just want to cache downloaded data, like profile pics; will be auto deleted by the system if it is low on room unless you specify with a special do-not-delete flag.
tmp: temporary files, deleted when your app is not running
For a full explanation check out File System Programming Guide and QA1719.
From following SO Answer:
You cannot write to applications bundle, it is read-only,
You can write files to document directory.
NSError *error;
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // or [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [docPath stringByAppendingPathComponent:#"beg_counter.txt"];
[level_cnt_beg writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
you can also save files to temp directory and Librarydirectory, for more info read this documentation, Where you should put your files
Thanks
I've looked through the Apple documentation on this point and other questions here, but cannot find a means of getting a consistent path to the documents directory.
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *urls = [fm URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *directory = [urls lastObject];
This produces a different path each time due to one component.
Example:
file:///var/mobile/Containers/Data/Application/CA708CF5-0E1B-414D-A795-31A8BB884BA5/Documents
Next run:
file:///var/mobile/Containers/Data/Application/2C96E341-85EF-485D-AC19-F8844B0880C3/Documents
I realize I need some kind of relative path here but I cannot figure out how to get it. How can I get to the Documents directory consistently to both write and read a file my app will produce?
The path is determined on installation. Each time you run your app in the simulator, it will be removed and reinstalled. Hence the differernt path. So you don't need to worry about this.
I was using
NSURL *applicationDocumentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
to get the application directory in the IOS simulator. In my previous projects, I get path like:
Users/username/Library/Application%20Support/iPhone%20Simulator/7.1-64/Applications/30CF9489-8AE3-49D4-9E01-DC14EBA2E08D/Documents/
However, in one of my projects, it returns
Users/username/Library/Application%20Support/iPhone%20Simulator/7.1-64/Applications/30CF9489-8AE3-49D4-9E01-DC14EBA2E08D/Library/Documentation
Why they return two different paths while I am using the same method?
Because in the 2nd case you are using NSDocumentationDirectory instead of NSDocumentDirectory.