Currently (2016), Apple is recommending more and more to use APIs related to NSURL URLs, NSFileManager , etc.
To get the document catalog in iOS and Swift 2 use
let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
try! safe in this case because this standard directory is guaranteed to exist.
Then add the appropriate path component, e.g. sqlite file
let databaseURL = documentDirectoryURL.URLByAppendingPathComponent("MyDataBase.sqlite")
Now check if the file exists with checkResourceIsReachableAndReturnError NSURL .
let fileExists = databaseURL.checkResourceIsReachableAndReturnError(nil)
If you need an error, pass an NSError pointer to the parameter.
var error : NSError? let fileExists = databaseURL.checkResourceIsReachableAndReturnError(&error) if !fileExists { print(error) }
Swift 3+:
let documentDirectoryURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let databaseURL = documentDirectoryURL.appendingPathComponent("MyDataBase.sqlite")
checkResourceIsReachable is marked as can throw
do { let fileExists = try databaseURL.checkResourceIsReachable() // handle the boolean result } catch let error as NSError { print(error) }
To consider only the logical return value and ignore the error, use the nil-coalescing operator
let fileExists = (try? databaseURL.checkResourceIsReachable()) ?? false