I'm trying to create a connection between my program and a database located in /Documents
of the app. When the code is built using on the simulator, it successfully opens the database; however, when I run the code on an iOS device, it can't find the file.
This is the code that I use:
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
let db = try! Connection("(path)/Database.db")
These are the contents of the variable path
when I run the code on the simulator:
/Users/xxxx/Library/Developer/CoreSimulator/Devices/EFD14A1B-7207-4840-9ACE-8E44A269CC70/data/Containers/Data/Application/58D150B9-E242-4857-B06C-DA28C88A26D0/Documents
And these are the contents of the variable path
when I run the code on an iOS device:
/var/mobile/Containers/Data/Application/4EC93D76-4E99-4552-855A-48C1D9346449/Documents
Xcode version: 12.0
iOS device: iPhone X
iOS version: 14.1
Edit
I tried to use this code to copy the database from the app bundle to the document directory, but it gives the error Unable to copy file
:
copyFileToDocumentsFolder(nameForFile: "Database", extForFile: "db")
func copyFileToDocumentsFolder(nameForFile: String, extForFile: String) {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destURL = documentsURL.appendingPathComponent(nameForFile).appendingPathExtension(extForFile)
guard let sourceURL = Bundle.main.url(forResource: nameForFile, withExtension: extForFile)
else {
print("Source File not found.")
return
}
let fileManager = FileManager.default
do {
try fileManager.copyItem(at: sourceURL, to: destURL)
} catch {
print("Unable to copy file")
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…