87

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?

Robin Daugherty
  • 7,115
  • 4
  • 45
  • 59
jwknz
  • 6,598
  • 16
  • 72
  • 115

20 Answers20

54

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.
Zaster
  • 860
  • 7
  • 6
49

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.

Vahid
  • 3,352
  • 2
  • 34
  • 42
  • 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") }` – App Dev Guy May 07 '18 at 02: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 Oct 06 '20 at 11:00
  • @Muz, Try it on simulator and copy and past file path in Terminal or Finder > Go > Go to Folder. – Vahid Oct 07 '20 at 08: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 Oct 09 '20 at 06: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).

Hiren Dhamecha
  • 658
  • 5
  • 15
Chris Chen
  • 5,307
  • 4
  • 45
  • 49
  • 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 Apr 20 '12 at 05: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 Apr 20 '12 at 14:25
  • 1
    Since the Simulator folders keep changing I am using SimPholders, which localizes them: https://simpholders.com/ – lukas_o Mar 18 '16 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. – Ammar Mujeeb Mar 06 '19 at 07:48
  • what if my app does not run on simulator? – Awais Fayyaz Sep 24 '20 at 11:01
23

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

staticVoidMan
  • 19,275
  • 6
  • 69
  • 98
12

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

Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105
Ivan Iliev
  • 121
  • 1
  • 5
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
qwerty
  • 2,065
  • 2
  • 28
  • 39
Rocky Balboa
  • 784
  • 10
  • 25
  • 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 Aug 20 '18 at 23:54
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

Jody Hagins
  • 27,943
  • 6
  • 58
  • 87
10

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)

ganzogo
  • 2,516
  • 24
  • 36
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

Nike Kov
  • 12,630
  • 8
  • 75
  • 122
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.

Ely
  • 8,259
  • 1
  • 54
  • 67
4

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.

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/

randomor
  • 5,329
  • 4
  • 46
  • 68
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
John Scalo
  • 3,194
  • 1
  • 27
  • 35
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).

msrd0
  • 7,816
  • 9
  • 47
  • 82
clearwater82
  • 1,746
  • 14
  • 9
3

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.
Black Mamba
  • 13,632
  • 6
  • 82
  • 105
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
pkamb
  • 33,281
  • 23
  • 160
  • 191
1

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");
}
Community
  • 1
  • 1
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
  • I'll have a look at this - it's been awhile since I looked at core data :-) – jwknz Apr 14 '17 at 07: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 – Inder Kumar Rathore Apr 14 '17 at 08:54
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

Guri S
  • 1,083
  • 11
  • 12
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.

Andreas Braun
  • 161
  • 1
  • 4