Where is my database file in xcode project - ios

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/

Related

Cannot get mainBundle resources (returns null)

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

How to get a shorter path to a file of my Xcode project

I have to share my OS X app, all the paths I have used for files used by project are linked to my username and the structure of my computer.
Is there a way to have paths related to my project so that once my project is shared the user may not get in troubles caused by 'file not found'.
I would move the used files of the project, into the project but then I don't know how to let this happen:
actual paths, what I use now:
/Users/???username???/XCode/projectName/fileName.txt
what I would like to use in my code:
function(path: fileName.txt)
how don't know how to make the paths this short, not caring about the users directories since the files I'm going to use are all inside my project.
I am very confused. Thank you.
There is actually an easy way to read files from your project directory:
NSError *error = nil;
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"txt"];
NSString *dataContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
So in dataContent you have the content of the file as an NSString instance.

Xcode 6 iPhone Simulator Application Support location

In Xcode 6, I have an app I'm using Core Data in, but there is no folder in Application Support for the iOS 8 iPhone Simulator. Where are my files and Core Data sqlite database being stored?
The simulator directory has been moved with Xcode 6 beta to...
~/Library/Developer/CoreSimulator
Browsing the directory to your app's Documents folder is a bit more arduous, e.g.,
~/Library/Developer/CoreSimulator/Devices/4D2D127A-7103-41B2-872B-2DB891B978A2/data/Containers/Data/Application/0323215C-2B91-47F7-BE81-EB24B4DA7339/Documents/MyApp.sqlite
I would suggest that you use SimPholders to find your Simulator files. It is a menu bar item that tracks your simulator apps and lets you go directly to their folders and content. It's awesome.
I found SimulatorManager application very useful. It takes you directly to the application folder of installed simulators. I have tried with 7.1, 8.0 and 8.1 simulators.
SimulatorManager resides as an icon in the system tray and provides an option to "Launch At Login".
Note: This works only with Xcode 6 (6.1.1 in my case) and above.
Hope that helps!
To know where your .sqlite file is stored in your AppDelegate.m add the following code
- (NSURL *)applicationDocumentsDirectory
{
NSLog(#"%#",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
now call this method in AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//call here
[self applicationDocumentsDirectory];
}
This worked for me in swift:
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
println("App Path: \(dirPaths)")
I wrestled with this for some time. It became a huge pain to simply get to my local sqlite db. I wrote this script and made it a code snippet inside XCode. I place it inside my appDidFinishLaunching inside my appDelegate.
//xcode 6 moves the documents dir every time. haven't found out why yet.
#if DEBUG
NSLog(#"caching documents dir for xcode 6. %#", [NSBundle mainBundle]);
NSString *toFile = #"XCodePaths/lastBuild.txt"; NSError *err = nil;
[DOCS_DIR writeToFile:toFile atomically:YES encoding:NSUTF8StringEncoding error:&err];
if(err)
NSLog(#"%#", [err localizedDescription]);
NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleName"];
NSString *aliasPath = [NSString stringWithFormat:#"XCodePaths/%#", appName];
remove([aliasPath UTF8String]);
[[NSFileManager defaultManager] createSymbolicLinkAtPath:aliasPath withDestinationPath:DOCS_DIR error:nil];
#endif
This creates a simlink at the root of your drive. (You might have to create this folder yourself the first time, and chmod it, or you can change the location to some other place) Then I installed the xcodeway plugin https://github.com/onmyway133/XcodeWay
I modified it a bit so that it will allow me to simply press cmd+d and it will open a finder winder to my current application's persistent Documents directory. This way, not matter how many times XCode changes your path, it only changes on run, and it updates your simlink immediately on each run.
I hope this is useful for others!
Open finder>Library>Developer>CoreSimulator>Devices
Then Change Arrangement icon from finder select Date Added
Select your app >data>Container>data>Applications>
choose your app >Documents>Here is your db file
In my case:
/Users/pluto/Library/Developer/CoreSimulator/Devices/A75107D2-A535-415A-865D-978B2555370B/data/Containers/Data/Application/265A12BC-FF5B-4235-B5EF-6022B83754B4/Documents/dboPhotoBucket.sqlite
Otherwise do this :
NSLog(#"app dir: %#",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
- It will print the full path to data folder.
Swift:
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
println("App Path: \(dirPaths)")
Use Finder-->go to folder and enter given basepath to reach application folders
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSLog(#"%#",basePath);
The simulator puts the file in ~/Library/Developer/CoreSimulator/Devices/... but the path after /Devices is different for everyone.
Use this handy method. It returns the path of the temporary directory for the current user and takes no argument.
NSString * NSTemporaryDirectory ( void );
So in my ViewController class I usually put this line in my viewDidLoad just for a reference when I need to grab my CoreData stored file. Hope this helps.
NSLog(#"FILE PATH :%#", NSTemporaryDirectory());
(Note: to go to the path, from the finder menu click on Go and type ~/Library to open hidden directory then in the Finder Window you can click on the path shown on your console.)
This location has, once again, changed, if using Swift, use this to find out where the folder is (this is copied from the AppDelegate.swift file that Apple creates for you so if it doesn't work on your machine, search in that file for the right syntax, this works on mine using Xcode 6.1 and iOS 8 simulator):
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
println("Possible sqlite file: \(urls)")
The simulators are located under:
~/Library/Developer/CoreSimulator/
Here, they are listed as directories with UUID names. Use sort by 'Date modified' to find the latest one. Inside navigate to:
/data/Containers/Data/Application/
Here you will get a list of all the applications on that device. You can again sort this to get the latest app.
NOTE: Xcode changes the directory name every time you run the app, so don't rely on making alias/short cuts on desktop.
The easiest way is to use the app here, which does everything automatically.
I created this script that will zip the latest app built for any simulator and zip it to the desktop.
https://gist.github.com/Gerst20051/8ca49d5afbf09007b3696fab6e9f425c
#!/bin/bash
DESTINATION_DIR="$HOME/Desktop"
APP_PATH=$(find ~/Library/Developer/CoreSimulator/Devices/*/data/Containers/Bundle/Application/*/*.app -type d -maxdepth 0 -print0 | xargs -0 ls -td | head -n1)
APP_DIRNAME=$(dirname "$APP_PATH")
APP_BASENAME=$(basename "$APP_PATH")
FILE_NAME="${APP_BASENAME%.*}"
cd "$APP_DIRNAME"
zip -qr "$DESTINATION_DIR/$FILE_NAME.zip" "$APP_BASENAME"
In Swift 4 or Swift 5 you can use NSHomeDirectory().
The easiest way in Xcode 10 (or Xcode 11) is to pause your app (like when it hits a breakpoint) and run this line in the debugger console:
po NSHomeDirectory()
po stands for print object and prints most things
1. NSTemporaryDirectory() gives this:
/Users/spokaneDude/Library/Developer/CoreSimulator/Devices/1EE69744-255A-45CD-88F1-63FEAD117B32/data/Containers/Data/Application/199B1ACA-A80B-44BD-8E5E-DDF3DCF0D8D9/tmp
2. remove "/tmp" replacing it with "/Library/Application Support/<app name>/" --> is where the .sqlite files reside
With Swift 4, you can use the code below to get your app's home directory. Your app's document directory is in there.
print(NSHomeDirectory())
I think you already know that your app's home directory is changeable, so if you don't want to add additional code to your codebase, SimPholder is a nice tool for you.
And further more, you may wonder is there a tool, that can help you save time from closing and reopening same SQLite database every time after your app's home directory be changed. And the answer is yes, a tool I know is SQLiteFlow. From it's document, it says that:
Handle database file name or directory changes. This makes SQLiteFlow can work friendly with your SQLite database in iOS simulator.
Here is the sh for last used simulator and application. Just run sh and copy printed text and paste and run command for show in finder.
#!/bin/zsh
lastUsedSimulatorAndApplication=`ls -td -- ~/Library/Developer/CoreSimulator/Devices/*/data/Containers/Data/Application/*/ | head -n1`
echo $lastUsedSimulatorAndApplication

Where to put txt file when running iOS simulator

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"];

read entire .m file (from bundle) as a string in iOS

I am trying to read entire .m file in a string using code:
NSString* fullFileName = #"file.m";
NSString* fileName = [[fullFileName lastPathComponent] stringByDeletingPathExtension];
NSString* extension = [fullFileName pathExtension];
NSString* filePath =[[NSBundle mainBundle] pathForResource:fileName ofType:extension];
NSString* fileTextContent=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
But it returns null.
Is it possible to read .m file from bundle in a string in iOS?
It's possible, but you should make sure the .m file is in the bundle first (they aren't by default).
Right click on the app under the products folder in Xcode, select "Reveal in Finder", then right click on the app in finder and select "Show Package contents" to see what's in the bundle.
If you need to add it, you can do that under the project settings in xcode > build phases > copy files phase.
Including .m files in the bundle would be somewhat strange though. There's almost certainly a better way to do whatever it is you're trying to do. Maybe if you went into more detail on what that is, people could suggest them.

Resources