92

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?

0

20 Answers 20

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.
7
  • 13
    In step 3, line 3, I needed to replace Documents with Library/Application\ Support and then it worked a treat, thanks!
    – Chris
    Commented Mar 31, 2017 at 21:37
  • 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.sqlite
    – ljubiccica
    Commented Jun 7, 2019 at 6:23
  • I used the question below to get the director, then I open the database with the last line here.
    – sgelves
    Commented Apr 21, 2020 at 11:24
  • This is brilliant! Works great as an application. Thank you!
    – dbDev
    Commented Jun 20, 2022 at 21:43
  • brew install --cask db-browser-for-sqlite Commented Mar 23, 2023 at 0:09
51

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.

4
  • 6
    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") } Commented May 7, 2018 at 2:09
  • 1
    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?
    – Muz
    Commented Oct 6, 2020 at 11:00
  • @Muz, Try it on simulator and copy and past file path in Terminal or Finder > Go > Go to Folder.
    – Vahid
    Commented Oct 7, 2020 at 8:28
  • @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.
    – Muz
    Commented Oct 9, 2020 at 6:39
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).

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?
    – jwknz
    Commented Apr 20, 2012 at 5:43
  • 1
    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.
    – Chris Chen
    Commented Apr 20, 2012 at 14:25
  • 1
    Since the Simulator folders keep changing I am using SimPholders, which localizes them: simpholders.com
    – lukas_o
    Commented Mar 18, 2016 at 13:08
  • 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. Commented Mar 6, 2019 at 7:48
  • what if my app does not run on simulator? Commented Sep 24, 2020 at 11:01
25

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

1
  • Solution 2 requires a import CoreData
    – Jonny
    Commented Jul 2 at 1:24
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 ;)

2
  • Thanks bro, you save my day.
    – user5570620
    Commented Jan 21, 2016 at 13:21
  • 2
    it is not in documents but in Library folder. Thanks for your answer Commented Dec 5, 2016 at 19:33
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
1
  • 1
    To get the device id: Open terminal and paste instruments -s devices Find the iPhone model and in the end it has device id
    – Pulkit
    Commented Aug 20, 2018 at 23:54
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)

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

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

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.

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.

2
  • 1
    And it's awesome. Thanks! Commented Nov 18, 2020 at 20:58
  • 1
    Perfect! I've been looking for such a tool for quite some time now. Thanks, Ron! Commented Apr 19, 2022 at 9:16
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.
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/

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
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).

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");
}
2
  • I'll have a look at this - it's been awhile since I looked at core data :-)
    – jwknz
    Commented Apr 14, 2017 at 7:17
  • @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 method Commented Apr 14, 2017 at 8:54
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
1

Just add in viewDidLoad:

debugPrint(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))
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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.