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

IosCore Data

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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

4. (Optional) Convert this workflow to application, save it and drag it to your dock. To refresh the database just click on the app icon.

Solution 2 - Ios

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.

Solution 3 - Ios

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

Solution 4 - Ios

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.

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

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

> Finder > Go > Go to folder

Solution 5 - Ios

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][2] to check the contents of your SQLite DB.

Worked like a charm for me ;)

[2]: http://sqlitebrowser.org/ "SQLiteBrowser"

Solution 6 - Ios

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:

instruments -s devices

Solution 7 - Ios

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

Solution 8 - Ios

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)

Solution 9 - Ios

  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

Solution 10 - Ios

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.

Solution 11 - Ios

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/

Solution 12 - Ios

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

Solution 13 - Ios

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.

Solution 14 - Ios

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

Here is how to get the application data:

https://stackoverflow.com/questions/6121613/browse-the-files-created-on-a-device-by-the-ios-application-im-developing-on-w

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

Solution 15 - Ios

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

Solution 16 - Ios

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

Solution 17 - Ios

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 [tag:swift]

/**
 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 [tag:objective-c]

/**
 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");
}

Solution 18 - Ios

Just add in viewDidLoad:

debugPrint(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))

Solution 19 - Ios

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.

Solution 20 - Ios

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjwknzView Question on Stackoverflow
Solution 1 - IosZasterView Answer on Stackoverflow
Solution 2 - IosVahidView Answer on Stackoverflow
Solution 3 - IosChris ChenView Answer on Stackoverflow
Solution 4 - IosstaticVoidManView Answer on Stackoverflow
Solution 5 - IosIvan IlievView Answer on Stackoverflow
Solution 6 - IosRocky BalboaView Answer on Stackoverflow
Solution 7 - IosJody HaginsView Answer on Stackoverflow
Solution 8 - IosganzogoView Answer on Stackoverflow
Solution 9 - IosNike KovView Answer on Stackoverflow
Solution 10 - IosElyView Answer on Stackoverflow
Solution 11 - IosrandomorView Answer on Stackoverflow
Solution 12 - Iosclearwater82View Answer on Stackoverflow
Solution 13 - IosBlack MambaView Answer on Stackoverflow
Solution 14 - IosAntonín KarásekView Answer on Stackoverflow
Solution 15 - IosBharath RaguView Answer on Stackoverflow
Solution 16 - IosJohn ScaloView Answer on Stackoverflow
Solution 17 - IosInder Kumar RathoreView Answer on Stackoverflow
Solution 18 - IosAntons AleksandrovsView Answer on Stackoverflow
Solution 19 - IosAndreas BraunView Answer on Stackoverflow
Solution 20 - IosGuri SView Answer on Stackoverflow