[ad_1]
In my iOS app, my database is within the folder of Utility assist/myDatabase folder. Hare are codes to get this folder created if not exist:
class MyDatabaseURLHelper {
personal databaseBase: URL {
let baseDir: FileManager.SearchPathDirectory =
.applicationSupportDirectory
let subDir = "myDatabase"
var url = FileManager.default.urls(
for: baseDir,
in: .userDomainMask).first!.appendPathComponent(subDir)
return url
}
func databaseURL() -> URL? {
var url: URL? = databaseBase
let dbName = "MyDatabaseFile"
if !FileManager.default.fileExists(atPath: url.path) {
do {
strive FileManager.default.createDirectory(
atPath: databaseBase.path,
withIntermediateDirectories: true,
attributes: nil)
} catch {
url = nil
}
return url?.appendPathComponent(dbName)
}
}
I’ve examined above codes. The database sub folder is created if no exist(first time), and the database url seems to be positive.
Here’s a snip of my codes to load database:
let modelName = "MyDatabase"
let container = NSPersistentContainer(title: modelName)
let url = MyDatabaseURLHelper().databaseURL()!
let storeDesription = NSPersistentStoreDescription(url: url)
storeDesription.shouldInferMappingModelAutomatically = true
storeDesription.shouldMigrateStoreAutomatically = true
container.persistentStoreDescriptions = [storeDesription]
container.loadPersistentStores() {
(storeDescription, error) in
if let error = error as NSError? {
let msg = "Unresolved error (error), (error.userInfo)"
fatalError(msg) // <- I acquired exception right here! if database file doesn't exist first time.
}
}
return container // No errors if database exists
My app runs OK for present customers since they’ve db file. Nonetheless, for brand new customers, I acquired my app crashes. New customers do not have database at their first time run. I verified the identical lead to my Xcode simulators.
The next is error message:
*"Unresolved error Error Area=NSCocoaErrorDomain Code=256 "The file “MyDatabase” couldn’t be opened." UserInfo={NSFilePath=/Customers/.../Utility/8DBC6D4F-967C-433D-9B28-60451CDAECDB/Library/Utility Help/myDatabase, "NSSQLiteErrorDomain": 14]"*
Unsure what has been modified in latest iOS (15.4). What’s lacking in loading persistence retailer?
[ad_2]
