How can I check what is stored in my Core Data Database?
Asked Answered
N

20

90

I am making an app that relies on Core Data. I am able to enter data into a text field and store it.

But I need to know if the data is being stored.

I am trying to make a detailView to my tableView and I am not getting any results. Now I am wondering is that because I am doing something wrong with my code, or is the data nto being stored properly.

How can I see what is stored in the app's CoreData database?

Nonpayment answered 20/4, 2012 at 2:56 Comment(0)
C
41

If you use sqlite as the storage media for Core Data, you can run your app in simulator and try to check the database file which is located in the sandbox's Library folder.

The path shall be something like: ~/Library/Application Support/iPhone Simulator/5.1/Applications/3BF8A4B3-4959-4D8F-AC12-DB8EF4C3B6E1/Library/YourAppName.sqlite

To open the sqlite file, you need a tool. I use a free tool called Liya (http://itunes.apple.com/us/app/liya/id455484422?mt=12).

Confiture answered 20/4, 2012 at 3:19 Comment(5)
Hi:-) I have that program abs didn't even think of that:-) but it is not based on a SQLite file. However there is an SQLite being generated by default isnt there? It has the projects name?Nonpayment
if you created the Xcode project with "Core Data" option ticked, yes. you shall check your AppDelegate.m file trying to find the what type of file is used for Core Data storage.Confiture
Since the Simulator folders keep changing I am using SimPholders, which localizes them: simpholders.comConform
only problem i face is that whatever tool i may use like Liya or DBSqlitebrowser if the relation is one to many then i cant track the related data. Like in one to one db shows generated id in ZID column which is traceable in connected entity but in one to many no colomn is created nor any id that can relate them. -In realmBrowser i can easily see objects even incase of one to many.Sanatory
what if my app does not run on simulator?Clamshell
W
57

Here is my solution(works on iOS 9):

I use an automator/bash script that open the database in sqllitebrowser. the script finds the latest installed app in the simulator. Instructions:

  1. Install DB Browser for SQLite (http://sqlitebrowser.org/)
  2. Create new workflow in Apple Automator.
  3. Drag "Run Shell script block" and paste this code:
cd ~/Library/Developer/CoreSimulator/Devices/
cd `ls -t | head -n 1`/data/Containers/Data/Application 
cd `ls -t | head -n 1`/Documents
open -a DB\ Browser\ for\ SQLite ./YOUR_DATABASE_NAME.sqlite

enter image description here

  1. (Optional) Convert this workflow to application, save it and drag it to your dock. To refresh the database just click on the app icon.
Woodland answered 18/5, 2016 at 12:50 Comment(7)
In step 3, line 3, I needed to replace Documents with Library/Application\ Support and then it worked a treat, thanks!Inflame
This works for me in Xcode 10 cd ~/Library/Developer/CoreSimulator/Devices/ cd ls -dt */ | head -n 1/data/Containers/Data/Application cd ls -dt */ | head -n 1/Library/Application\ Support open -a DB\ Browser\ for\ SQLite ./YOUR_DATABASE_NAME.sqlitePetrarch
I used the question below to get the director, then I open the database with the last line here.Flogging
This is brilliant! Works great as an application. Thank you!Cockeyed
brew install --cask db-browser-for-sqliteAlba
Thx man u save my day. core data is just .... ^^Velarize
I followed the steps above to open the Documents folder, but there are no files in this folder. How is this going? What am I did wrong?Decurrent
V
50

Swift 4, 5

Add this line in AppDelegate >> didFinishLaunchingWithOptions function:

print("Documents Directory: ", FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last ?? "Not Found!")

Your modelName.sqlite file will be there.

You can open it with any SQLite browser tools like http://sqlitebrowser.org/ that is free.

Viceroy answered 1/3, 2018 at 7:5 Comment(4)
This worked better for me: // Use this for inspecting the Core Data if let directoryLocation = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).last { print("Documents Directory: \(directoryLocation)Application Support") }Spheroidicity
The code prints that "Documents Directory: file:///var/mobile/Containers/Data/Application/C8A58192-D5CD-4278-8AC6-905C883C73A4/Documents/". There is no "modelName.sqlite". How to get the whole directory?Yung
@Muz, Try it on simulator and copy and past file path in Terminal or Finder > Go > Go to Folder.Viceroy
@Vahid, I found that the reason is that I was not running on simulator but on device. The output is different on simulator and device.Yung
C
41

If you use sqlite as the storage media for Core Data, you can run your app in simulator and try to check the database file which is located in the sandbox's Library folder.

The path shall be something like: ~/Library/Application Support/iPhone Simulator/5.1/Applications/3BF8A4B3-4959-4D8F-AC12-DB8EF4C3B6E1/Library/YourAppName.sqlite

To open the sqlite file, you need a tool. I use a free tool called Liya (http://itunes.apple.com/us/app/liya/id455484422?mt=12).

Confiture answered 20/4, 2012 at 3:19 Comment(5)
Hi:-) I have that program abs didn't even think of that:-) but it is not based on a SQLite file. However there is an SQLite being generated by default isnt there? It has the projects name?Nonpayment
if you created the Xcode project with "Core Data" option ticked, yes. you shall check your AppDelegate.m file trying to find the what type of file is used for Core Data storage.Confiture
Since the Simulator folders keep changing I am using SimPholders, which localizes them: simpholders.comConform
only problem i face is that whatever tool i may use like Liya or DBSqlitebrowser if the relation is one to many then i cant track the related data. Like in one to one db shows generated id in ZID column which is traceable in connected entity but in one to many no colomn is created nor any id that can relate them. -In realmBrowser i can easily see objects even incase of one to many.Sanatory
what if my app does not run on simulator?Clamshell
C
24

The other solutions are either old or does not direct you easily or quickly to the SQLite files, so I came up with my own solution using FileManager.SearchPathDirectory.applicationSupportDirectory that gets the exact path where the sqlite file will be.

Solution #1 using FileManager.default:
func whereIsMySQLite() {
    let path = FileManager
        .default
        .urls(for: .applicationSupportDirectory, in: .userDomainMask)
        .last?
        .absoluteString
        .replacingOccurrences(of: "file://", with: "")
        .removingPercentEncoding
    
    print(path ?? "Not found")
}
Solution #2 using NSPersistentContainer.defaultDirectoryURL():
func whereIsMySQLite() {
    let path = NSPersistentContainer
        .defaultDirectoryURL()
        .absoluteString
        .replacingOccurrences(of: "file://", with: "")
        .removingPercentEncoding

    print(path ?? "Not found")
}

Either whereIsMySQLite() will print the path which you can simply copy-paste on your Mac here:

Finder > Go > Go to folder

Causal answered 25/1, 2019 at 11:34 Comment(1)
Solution 2 requires a import CoreDataLafountain
E
13

The folder where the db is stored has recently been changed and is not where you'd expect to find it. Here's what I used to solve this: First add this code to your viewDidLoad or applicationDidFinishLaunching:

    #if TARGET_IPHONE_SIMULATOR
    // where are you?
    NSLog(@"Documents Directory: %@", [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
    #endif

Got this from here: where is the documents directory for the ios 8 simulator

This will reveal the actual location of your app in the console during runtime. Then use the SQLiteBrowser to check the contents of your SQLite DB.

Worked like a charm for me ;)

Escobar answered 9/11, 2015 at 9:21 Comment(2)
Thanks bro, you save my day.Anetteaneurin
it is not in documents but in Library folder. Thanks for your answerHayrick
T
12

As Far as macOS Sierra version 10.12.2 and Xcode 8 is concerned

The folder should be here:

/Users/$username$/Library/Developer/CoreSimulator/Devices/$DeviceID$/data/Containers/Data/Application/$ApplicationID$/Library/Application Support/xyz.sqlite

To get the device id - Open terminal and paste:

xcrun xctrace list devices
Treviso answered 25/1, 2017 at 11:44 Comment(1)
To get the device id: Open terminal and paste instruments -s devices Find the iPhone model and in the end it has device idBrundisium
S
11

In Swift 3, you have the the NSPersistentContainer and you can retrieve the path from there like this:

persistentContainer.persistentStoreCoordinator.persistentStores.first?.url

(Assuming you are only using one persistent store)

Sanbo answered 30/11, 2016 at 12:12 Comment(0)
U
10

As said before, you can use the sqllite command line tool.

However, you can also set the debug flag, which will dump out all sql commands as they execute through core data.

Edit the scheme, and add this in the "Arguments Passed on Launch"

-com.apple.CoreData.SQLDebug 1

Unification answered 20/4, 2012 at 4:17 Comment(0)
F
6

1) Get path of sql database of your simulator.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"%@", [paths objectAtIndex:0]);

2) Open Finder. Press Cmd+Shift+G. Paste something, that you got from paragraph 1. Ex:

/Users/USERNAME/Library/Developer/CoreSimulator/Devices/701BAC5F-2A42-49BA-B733-C39D563208D4/data/Containers/Data/Application/DCA9E9C7-5FEF-41EA-9255-6AE9A964053C/Documents

3) Download in AppStore programm like SQLPro.

4) Open file in folder with name "ProjectName.sqlite".

GOOD JOB! You will see something like this: enter image description here

Foxhole answered 11/11, 2016 at 7:14 Comment(0)
G
5

Since no one has pointed out, how to get the sqlite DB from the physical device.

Here is how to get the application data:

Browse the files created on a device by the iOS application I'm developing, on workstation?

After opening the .xcappdata file (right click > Show Package Content), you will usually find the DB file at the AppData/Library/Application Support folder.

Grosswardein answered 25/10, 2019 at 17:39 Comment(0)
B
5

An easy and convenient way to locate the Core Data database and to view and analyse the content, is by using a tool like Core Data Lab.

More info here: https://betamagic.nl/products/coredatalab.html

Disclaimer: I'm the creator of this tool.

Buffoon answered 14/1, 2020 at 10:5 Comment(2)
And it's awesome. Thanks!Simplehearted
Perfect! I've been looking for such a tool for quite some time now. Thanks, Ron!Zeist
H
4

An answer for a noobs as I was, I spent quite a lot of time in figuring it out. Steps I followed are :

  1. Open finder and Press Command(Windows) + Shift + G.
  2. Go to the folder add ~/Library/Developer
  3. Search for the DB name you've created as in my case it was my.db in SQLite.
  4. Download and install DB browser for SQLite.
  5. Click open database.
  6. Now drag and drop the DB file from your finder.
Hardihood answered 16/9, 2017 at 5:52 Comment(0)
D
4

I found the best way to find and open the .sqlite database is use this script:

lsof -Fn -p $(pgrep YOUR_APP_NAME_HERE) | grep .sqlite$ | head -n1

For whatever reason, the output on my Mac always has an extra n character, so I had to copy and paste it to open command. Feel free to modify the above command if you've figured out the right command.

For the best SQLite browser, I'd recommend TablePlus.

Adopted from: https://lukaszlawicki.pl/how-to-quickly-open-sqlite-database-on-ios-simulator/

Dissertate answered 1/9, 2020 at 3:12 Comment(0)
M
4

Surprised no one has mentioned this, but assuming your Core Data store is sqlite, you can do a quick & dirty dump of its contents with no 3rd party tools by doing this in Terminal:

$ sqlite3 <path-to-file.sqlite>

// Dump everything
sqlite> .dump

// Dump just one type
sqlite> .dump ZSOMETYPE

// ^D to exit
Mesentery answered 10/2, 2021 at 16:3 Comment(0)
C
3

Download the SQLite Browser from here.

Run your app in the Simulator. The app should be copied to a path on your Mac that looks like:

/Users/$your username$/Library/Application Support/iPhone Simulator/$your iphone simulator version$/Applications/

Once you locate your app, you have to dig deeper to find the sqlite db (It's usually under Documents).

Cracknel answered 20/4, 2012 at 3:22 Comment(0)
M
2

I wasn't able to find it in the iPhone Simulator folder. Then I found out the folder by printing the doc path in log:

NSLog(@"The Path is %@", 
  [[[NSFileManager defaultManager] URLsForDirectory:
     NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);

and the path turns out be like this :

// /Users/<username>/Library/Developer/CoreSimulator/Devices/<app specific id>/data/Containers/Data/Application/<id>/Documents/coredata.sqlite
Marchpast answered 31/3, 2016 at 8:0 Comment(0)
E
2

If you've already access to sqlite, shm and wal files then run the commands in the terminal to merge the WAL file into the sqlite file.

$ sqlite3 persistentStore
sqlite> PRAGMA wal_checkpoint;
Press control + d

After running the above commands you can see the data in your sqlite file.


Utility to copy sqlite files to your desktops (do change the desktop path and give the absolute path, the ~ symbol won't work.

For iOS 10.0+ you can use persistentContainer.persistentStoreCoordinator.persistentStores.first?.url

I have created the Utility function that copies the sqlite file to your desired location (works only for simulator). You can use the utility it like

import CoreData


let appDelegate = UIApplication.shared.delegate as! AppDelegate
UTility.getSqliteTo(destinationPath: "/Users/inderkumarrathore/Desktop", persistentContainer: appDelegate.persistentContainer)

Here is definition of utility method for

/**
 Copies the sqlite, wal and shm file to the destination folder. Don't forget to merge the wal file using the commands printed int the console.
 @param destinationPath Path where sqlite files has to be copied
 @param persistentContainer NSPersistentContainer
*/
public static func getSqliteTo(destinationPath: String, persistentContainer: NSPersistentContainer) {
  let storeUrl = persistentContainer.persistentStoreCoordinator.persistentStores.first?.url
  
  let sqliteFileName = storeUrl!.lastPathComponent
  let walFileName = sqliteFileName + "-wal"
  let shmFileName = sqliteFileName + "-shm"
  //Add all file names in array
  let fileArray = [sqliteFileName, walFileName, shmFileName]
  
  let storeDir = storeUrl!.deletingLastPathComponent()
  
  // Destination dir url, make sure file don't exists in that folder
  let destDir = URL(fileURLWithPath: destinationPath, isDirectory: true)

  do {
    for fileName in fileArray {
      let sourceUrl = storeDir.appendingPathComponent(fileName, isDirectory: false)
      let destUrl = destDir.appendingPathComponent(fileName, isDirectory: false)
      try FileManager.default.copyItem(at: sourceUrl, to: destUrl)
      print("File: \(fileName) copied to path: \(destUrl.path)")
    }
  }
  catch {
    print("\(error)")
  }
  print("\n\n\n ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ NOTE ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~\n")
  print("In your terminal run the following commands to merge wal file. Otherwise you may see partial or no data in \(sqliteFileName) file")
  print("\n-------------------------------------------------")
  print("$ cd \(destDir.path)")
  print("$ sqlite3 \(sqliteFileName)")
  print("sqlite> PRAGMA wal_checkpoint;")
  print("-------------------------------------------------\n")
  print("Press control + d")      
}

For

/**
 Copies the sqlite, wal and shm file to the destination folder. Don't forget to merge the wal file using the commands printed int the console.
 @param destinationPath Path where sqlite files has to be copied
 @param persistentContainer NSPersistentContainer
 */
+ (void)copySqliteFileToDestination:(NSString *)destinationPath persistentContainer:(NSPersistentContainer *)persistentContainer {
  NSError *error = nil;
  NSURL *storeUrl = persistentContainer.persistentStoreCoordinator.persistentStores.firstObject.URL;
  NSString * sqliteFileName = [storeUrl lastPathComponent];
  NSString *walFileName = [sqliteFileName stringByAppendingString:@"-wal"];
  NSString *shmFileName = [sqliteFileName stringByAppendingString:@"-shm"];
  //Add all file names in array
  NSArray *fileArray = @[sqliteFileName, walFileName, shmFileName];
  
  // Store Directory
  NSURL *storeDir = storeUrl.URLByDeletingLastPathComponent;

  // Destination dir url, make sure file don't exists in that folder
  NSURL *destDir = [NSURL fileURLWithPath:destinationPath isDirectory:YES];
  
  for (NSString *fileName in fileArray) {
    NSURL *sourceUrl = [storeDir URLByAppendingPathComponent:fileName isDirectory:NO];
    NSURL *destUrl = [destDir URLByAppendingPathComponent:fileName isDirectory:NO];
    [[NSFileManager defaultManager] copyItemAtURL:sourceUrl toURL:destUrl error:&error];
    if (!error) {
      RLog(@"File: %@ copied to path: %@", fileName, [destUrl path]);
    }
  }
  
  
  NSLog(@"\n\n\n ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ NOTE ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~\n");
  NSLog(@"In your terminal run the following commands to merge wal file. Otherwise you may see partial or no data in %@ file", sqliteFileName);
  NSLog(@"\n-------------------------------------------------");
  NSLog(@"$ cd %@", destDir.path);
  NSLog(@"$ sqlite3 %@", sqliteFileName);
  NSLog(@"sqlite> PRAGMA wal_checkpoint;");
  NSLog(@"-------------------------------------------------\n");
  NSLog(@"Press control + d");
}
Encampment answered 14/4, 2017 at 6:41 Comment(2)
I'll have a look at this - it's been awhile since I looked at core data :-)Nonpayment
@JeffKranenburg Not an issue :), I faced the same problem and thought of making some solution to solve the problem of getting the core data sqlite store. And this method solve my purpose and I hope other guys may take benefit from this methodEncampment
V
1

Just add in viewDidLoad:

debugPrint(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))
Vaporish answered 3/5, 2018 at 12:10 Comment(0)
D
1

Open Mac OS terminal and type the following commands

xcrun simctl get_app_container booted com.ondevtratech.PlannerCoreData


xcrun simctl get_app_container booted <bundle <>identifier> 

To open a DB :

brew install --cask db-browser-for-sqlite

Open << App path: sql lite.app >> <<.sqlite DB path>>

For Example : open -a /Applications/DB\ Browser\ for\ SQLite.app /DTMPlanner.sqlite

Dextrous answered 1/2, 2022 at 6:2 Comment(0)
D
0

print("Documents Directory: ", FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last ?? "Not Found!")

Please add this line in applicationDidFinishLaunching of AppDelegate. It will give us the path of Documents. But database of core data is in ./Library/Application Support/ with the name projectname.sqlite.

Diabolize answered 10/2, 2021 at 22:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.