programing tip

Sqlite 파일 위치 핵심 데이터

itbloger 2020. 9. 15. 07:29
반응형

Sqlite 파일 위치 핵심 데이터


일반적으로 핵심 데이터 앱용 sqlite 스토어 파일은 다음 위치에 있습니다.

라이브러리> 응용 프로그램 지원> iPhone Simulator> 7.1 (또는 사용중인 버전)> 응용 프로그램> (앱이 포함 된 폴더)> 문서

폴더이지만 IOS 8에서는 찾을 수 없습니다. iPhone Simulator 폴더 안에 8.0 폴더 만 추가한다고 가정하지만 거기에는 없습니다. 아무도 그것을 찾을 수 있었습니까?


나는 sqlite 파일을 찾았으며 지금이 경로에 있습니다.

Library / Developer / CoreSimulator / Devices / (숫자 및 문자) / data / Containers / Data / Application / (숫자 및 문자) / Documents /

(숫자 및 문자)는 앱 / 컴퓨터에 고유하지만 다음과 같은 폴더를 나타냅니다. 779AE2245-F8W2-57A9-8C6D-98643B1CF01A

appDelegate.m으로 이동하여 아래로 스크롤하여 찾을 수있었습니다.

- (NSURL *)applicationDocumentsDirectory 

다음과 같이 반환 경로를 NSLogging합니다.

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory  inDomains:NSUserDomainMask] lastObject]);

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
 }

이름이 지정되지 않은 2 개의 폴더 / 문자 및 숫자 문자열로 찾기가 까다롭기 때문에 고유 한 경로를 제공하여 쉽게 찾을 수 있습니다.

Swift 4.2 :

let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
print(paths[0])

실제로 DB 파일의 위치를 ​​얻는 가장 간단한 방법은 언급되지 않았습니다.

XCode의 간단한 런타임 스위치이므로 소스 코드를 수정할 필요도 없습니다.

  1. 실행 버튼 옆에있는 스키마 편집 ...을 선택합니다.

    구성표 편집

  2. Run / Arguments를 선택하고 다음 두 가지 옵션을 추가합니다.

    -com.apple.CoreData.SQLDebug 1
    -com.apple.CoreData.Logging.stderr 1
    

    선택권

  3. 앱을 실행하면 로그에 다음이 표시됩니다.

    로그


이 간단한 3 단계 시도

  1. 에 다음 코드를 복사 didFinishLaunchingWithOptions하여 appdelegate.m그리고 전에 브레이크 포인트를 추가NSLog()

    (BOOL)application:(UIApplication *)application  
    
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@",[paths objectAtIndex:0]);
     }
    

또는 Swift에서 :

let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
print(paths[0])

여기에 이미지 설명 입력

2. Finder-> Go-> Go to folder를 열고 1 단계에서 복사 한 경로를 붙여 넣습니다.

여기에 이미지 설명 입력

3. 예 !!! 당신은 당신의 목적지에 있습니다.


앱이 Core Data를 사용하는 경우 터미널에서 sqlite 파일을 검색하기 만하면됩니다.

find ~ -name app_db_file_name.sqlite

결과는 앱이 포함 된 시뮬레이터 폴더의 전체 경로를 나열합니다.


나는이 한 줄짜리 ( Gist )를 해킹했습니다 .find ~/Library/Developer/CoreSimulator/Devices/ -name device.plist -exec sh -c "/usr/libexec/PlistBuddy -c \"print UDID\" '{}' | tr '\n' ' '" \; -exec sh -c "/usr/libexec/PlistBuddy -c \"print name\" '{}' | tr '\n' ' '" \; -exec sh -c "/usr/libexec/PlistBuddy -c \"print runtime\" '{}' | sed -n 's/com\.apple\.CoreSimulator.SimRuntime\.\(.*\)/\1/p'" \;

이것은 다음을 인쇄합니다.

14F313C8-3813-4E38-903E-2010C136B77B iPad Retina iOS-8-0
1F6B82A2-C467-479A-8CAF-074BE507AC8E iPad Air iOS-8-0
2DA83944-BE5D-4342-B330-08F67A932D8C iPad 2 iOS-7-1
48703432-A5C5-4606-9369-0D21B53EB1E8 iPhone 4s iOS-7-1
4AFB71CC-6752-4F9A-A239-4DC9CA53A8B8 iPhone 5s iOS-8-0
53A65771-DF50-4A5C-A8D2-4D1C3A5D0F60 iPhone 5 iOS-7-1
6B97C174-5914-4E89-8D17-943F0E2703BA iPhone 5 iOS-8-0
6C2DF3E9-FA26-4391-8B66-72E1467D6297 iPad 2 iOS-8-0
7F85E299-A3C2-4704-8B44-2984F6F995F5 iPad Retina iOS-7-1
8B9EDFFD-2240-476B-88AD-06ABE8F9FF51 iPhone 6 Plus iOS-8-0
97691E5D-5C38-4875-8AA7-C2B1E4ABCBB5 Resizable iPhone iOS-8-0
9BBF3408-6CA4-4CE0-BD4E-B02001F1262B iPhone 5s iOS-7-1
C9237847-F0AA-44BC-A74E-C08C2E0F7A6C Resizable iPad iOS-8-0
CC44C1BA-F39C-4410-AE34-4ABBD7806D45 iPad Air iOS-7-1
CDF4D811-5011-4464-8291-5CDA378375EA iPhone 6 iOS-8-0
E77DE00C-E244-4F25-A5E2-E6581614D5A2 iPhone 4s iOS-8-0

최신 정보:

누군가가 여기서 지적했듯이 xcrun simctl list devices비슷한 결과를 얻기 위해 실행할 수도 있습니다.

== Devices ==
-- iOS 7.0 --
-- iOS 7.1 --
    iPhone 4s (48703432-A5C5-4606-9369-0D21B53EB1E8) (Shutdown)
    iPhone 5 (53A65771-DF50-4A5C-A8D2-4D1C3A5D0F60) (Shutdown)
    iPhone 5s (9BBF3408-6CA4-4CE0-BD4E-B02001F1262B) (Shutdown)
    iPad 2 (2DA83944-BE5D-4342-B330-08F67A932D8C) (Shutdown)
    iPad Retina (7F85E299-A3C2-4704-8B44-2984F6F995F5) (Shutdown)
    iPad Air (CC44C1BA-F39C-4410-AE34-4ABBD7806D45) (Shutdown)
-- iOS 8.1 --
    iPhone 4s (0763EF65-DD0D-4FAD-84C7-2DE63D416526) (Shutdown)
    iPhone 5 (868ED444-8440-4115-AF37-F419CC682D2F) (Shutdown)
    iPhone 5s (E0455E5D-7315-4EC8-B05E-76284728244C) (Shutdown)
    iPhone 6 Plus (72554908-FF99-4B8F-9B87-65255ED08CFC) (Shutdown)
    iPhone 6 (32AA8133-53A4-4BE0-8CE5-0C7A87E81CAF) (Shutdown)
    iPad 2 (4AF84DE8-CBA2-47AE-A92A-0C0CEF9F41F8) (Booted)
    iPad Retina (69238B44-AAFD-4CD5-AAEA-C182D0BC300D) (Shutdown)
    iPad Air (E580AD99-0040-4EC1-B704-0C85567E6747) (Shutdown)
    Resizable iPhone (32E872FC-6513-41AB-A5B9-B23EB7D10DC8) (Shutdown)
    Resizable iPad (99997922-4A9F-4574-9E3E-EF45F893F4A2) (Shutdown)

Swift를 사용하는 경우 문서 디렉토리의 절대 경로를 반환합니다.

func applicationDirectoryPath() -> String {
    return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as String
}

시뮬레이터 내에서 Application 폴더와 Application data 폴더의 위치를 ​​찾기위한 bash 스크립트를 작성했습니다 . 여기에서 다운로드 할 수 있습니다 . 스크립트의 압축을 풀면 스크립트가있는 폴더로 이동하여 사용할 수 있습니다. 옵션없이 호출하면 설치된 iOS 시뮬레이터 목록이 제공됩니다. 그런 다음 옵션을 사용하여 프로그램을 찾을 수 있습니다. 쓰기:

./simulatorAppFolders -s "iPad Air" -i iOS-8-0 -a <MyApp>

iPad Air iOS 8 시뮬레이터에서 앱의 응용 프로그램 폴더와 홈 영역 폴더를 찾습니다. 예를 들면 다음과 같습니다.

MacBook-Air:_posts user$ ./simulatorAppFolders -s "iPad Air" -i iOS-8-0 -a MyApp
App folder = /Users/james/Library/Developer/CoreSimulator/Devices/6A9DEE93-FAEF-4BF4-9989-BC14CD38AEA0/data/Containers/Bundle/Application/8F64CD7F-A227-43D6-98AC-41D3919827CB
dataFolder = /Users/james/Library/Developer/CoreSimulator/Devices/6A9DEE93-FAEF-4BF4-9989-BC14CD38AEA0/data/Containers/Data/Application/96C40A21-5A5C-4399-839C-B155B8A72932

최신 정보

-d 옵션을 사용하여 장치 유형을 기반으로 검색 할 수있는 원본 스크립트에 대한 업데이트가 있습니다. 또한 응용 프로그램 및 응용 프로그램 문서를 찾을 수 있도록 일련의 합리적인 이름의 폴더를 만드는 또 다른 스크립트를 작성했습니다. 이 스크립트 는 홈 영역에 iOS_SIMULATORS라는 폴더를 만들고 거기에서 애플리케이션으로 쉽게 이동할 수 있습니다.


다음 콘솔 출력으로 시뮬레이터 폴더를 찾을 수있었습니다.

NSLog(@"app dir: %@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);

제 경우에는 (Xcode 6 베타)

app dir: file:///Users/user/Library/Developer/CoreSimulator/Devices/D00C56D4-DDA3-47B0-9951-27D3B9EC68E8/data/Applications/6ABF3E54-37F5-4AD1-A223-F7467F601FB6/Documents/

Michaels 답변에 따르면 Swift 3 용입니다.

    func applicationDirectoryPath() -> String {
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String
    }

Swift 3.0의 경우

let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
print(paths[0])

Xcode 8.2에서 Coredata의 위치를 ​​얻을 수 있습니다.


SWIFT 3의 경우 :

이 코드를 didFinishLaunchingWithOptions에 복사하여 붙여 넣으십시오.

 print(NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as String)

After new updates of Xcode I found that the sql files are now stored in new folder /Library/Application Support this could be a unique situation but if you did not found the sql files in document folder search them here:

~/Library/Developer/CoreSimulator/Devices/[@device_id@]/data/Containers/Data/Application/[@application_id@]/Library/Application Support/

before it was stored in Documents folder:

~/Library/Developer/CoreSimulator/Devices/[@device_id@]/data/Containers/Data/Application/[@application_id@]/Documents/


For swift 3

print(NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as String)

Like James Snook I created my own script to provide easier access to the simulator apps. I think it can be handy to many people getting here, other than me.

Unlike his script, mine is not a search tool, it creates a complete (and human readable) folder structure with all the devices/runtimes, and puts soft links to the apps in them.

You can get it in this Gist.

Run it every time you install an app in the simulator, or just run it every time you are going fetch an app for any reason (it will update, and open the devices folder in Finder).


If you haven't specified any directory then you can use the below code to print default directory:

print(NSPersistentContainer.defaultDirectoryURL())


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 it like

import CoreData


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

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.


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

Swift 3.x

찾아 didFinishLaunchingWithOptions은 당신의 기능을 AppDelegate에의 파일이이 코드를 과거.

let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)
print("\(path)")

스위프트 4.x

    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    print(paths[0])

스위프트 4.2

let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        print(paths[0])

다음 코드를 사용할 수 있습니다.

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    **print(persistentContainer.persistentStoreDescriptions)**
    return true
}

핵심 데이터 영구 저장소, 즉 sqlite의 위치를 ​​인쇄합니다.

참고 URL : https://stackoverflow.com/questions/24133022/sqlite-file-location-core-data

반응형