简体   繁体   中英

Copy Sqlite Database Behind CoreData

I want to access the Sqlite database backing CoreData, make a copy of it, and send it to an endpoint for remote troubleshooting. Is this possible?

My solution...

let fileManager = FileManager.default

let libraryURL = NSPersistentContainer.defaultDirectoryURL()

guard let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
    // handle error...
    return
}

// creating a folder in documents for ease of zipping and later removal
let dbURL = documentsURL.appendingPathComponent("db")
do {
    try fileManager.createDirectory(at: dbURL, withIntermediateDirectories: true, attributes: nil)
} catch {
    // handle error...
    return
}

do {
    let fileURLs = try fileManager.contentsOfDirectory(at: libraryURL, includingPropertiesForKeys: nil, options: [])
    for fileURL in fileURLs.filter({ $0.absoluteString.contains("<NAME_OF_CORE_DATA_STORE>") }) {
        let fileName = fileURL.lastPathComponent
        do {
            try fileManager.copyItem(at: fileURL, to: URL(string: "\(documentsURL.absoluteString)db/\(fileName)")!)
        } catch  {
            // handle error...
        }
    }
} catch {
    // handle error...
}

// finally, do something with the file (I zip and send to an endpoint)

Yes, possible. Just don't try and treat it as writable outside the core data ecosystem. Readable, no worries.

Copy all the parts from where it's written to. The default SQLite mode is journaled so you will get a wal file written as a counterpart.

You can interrogate the NSPersistentStore.url for the write location of your database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM