简体   繁体   中英

Swift - how to check for existing Core Data Store iOS

I'm working on an app that should have a starting window that will have an intro and then either a "Get Started" button if no existing core data store is found, and then if a store is present - it should have a "Continue Session" and "Start Over" buttons. Only problem I don't think my code for checking for a store is working - I'm putting this in the ViewController's viewDidLoad function:

override func viewDidLoad() {
    super.viewDidLoad()
    let defaultStorePath = NSBundle.mainBundle().pathForResource("LearnUSStateCapitals", ofType: "sqlite")
    let fileManager = NSFileManager.defaultManager()
    if defaultStorePath == nil {
        println("can't find store")
        generateSCA()
    } else {
        println("store found...I think")
        continueButton.hidden = false
    }

So all I'm getting is "can't find store" - even after running the app a few times. I've navigated to \\Library\\Developer\\CoreSimulator\\Devices\\blahblah\\data\\Containers\\Data\\Application\\blahblah\\Documents and do see my "LearnUSStateCapitals.sqlite" file there created at the time I first ran the app as is...

The reason I'm using if defaultStorePath == nil is because when I try if fileManager.fileExistsAtPath(defaultStorePath!) I get unexpectedly found nil while unwrapping an Optional value - why is this nil maybe the real question... thanks for any help

The file you can see is in the Application Documents directory, which is different from the main bundle. You can get a URL for the application documents directory with:

let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let appDocsURL : NSURL = urls[urls.count - 1] as NSURL
let defaultStoreURL = appDocsURL.URLByAppendingPathComponent("LearnUSStateCapitals.sqlite")

then use:

if !fileManager.fileExistsAtPath(defaultStoreURL.path!) {
    println("can't find store")
    generateSCA()
} else {
    println("store found...I think")
    continueButton.hidden = false
}

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