How to check if a file exists in the Documents directory in Swift?

前端 未结 12 2160
梦毁少年i
梦毁少年i 2020-11-28 21:19

How to check if a file exists in the Documents directory in Swift?

I am using [ .writeFilePath ] method to save an image into the Documents

12条回答
  •  旧时难觅i
    2020-11-28 21:37

    Nowadays (2016) Apple recommends more and more to use the URL related API of NSURL, NSFileManager etc.

    To get the documents directory in iOS and Swift 2 use

    let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, 
                                     inDomain: .UserDomainMask, 
                            appropriateForURL: nil, 
                                       create: true)
    

    The try! is safe in this case because this standard directory is guaranteed to exist.

    Then append the appropriate path component for example an sqlite file

    let databaseURL = documentDirectoryURL.URLByAppendingPathComponent("MyDataBase.sqlite")
    

    Now check if the file exists with checkResourceIsReachableAndReturnError of NSURL.

    let fileExists = databaseURL.checkResourceIsReachableAndReturnError(nil)
    

    If you need the error pass the 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 boolean return value and ignore the error use the nil-coalescing operator

    let fileExists = (try? databaseURL.checkResourceIsReachable()) ?? false
    

提交回复
热议问题