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

前端 未结 12 2097
梦毁少年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条回答
  • 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
    
    0 讨论(0)
  • 2020-11-28 21:37

    An alternative/recommended Code Pattern in Swift 3 would be:

    1. Use URL instead of FileManager
    2. Use of exception handling

      func verifyIfSqliteDBExists(){
          let docsDir     : URL       = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
          let dbPath      : URL       = docsDir.appendingPathComponent("database.sqlite")
      
          do{
              let sqliteExists : Bool = try dbPath.checkResourceIsReachable()
              print("An sqlite database exists at this path :: \(dbPath.path)")
      
          }catch{
              print("SQLite NOT Found at :: \(strDBPath)")
          }
      }
      
    0 讨论(0)
  • 2020-11-28 21:39

    works at Swift 5

        do {
            let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
            let fileUrl = documentDirectory.appendingPathComponent("userInfo").appendingPathExtension("sqlite3")
            if FileManager.default.fileExists(atPath: fileUrl.path) {
                print("FILE AVAILABLE")
            } else {
                print("FILE NOT AVAILABLE")
            }
        } catch {
            print(error)
        }
    

    where "userInfo" - file's name, and "sqlite3" - file's extension

    0 讨论(0)
  • 2020-11-28 21:41

    Very simple: If your path is a URL instance convert to string by 'path' method.

        let fileManager = FileManager.default
        var isDir: ObjCBool = false
        if fileManager.fileExists(atPath: yourURLPath.path, isDirectory: &isDir) {
            if isDir.boolValue {
                //it's a Directory path
            }else{
                //it's a File path
            }
        }
    
    0 讨论(0)
  • 2020-11-28 21:42

    For the benefit of Swift 3 beginners:

    1. Swift 3 has done away with most of the NextStep syntax
    2. So NSURL, NSFilemanager, NSSearchPathForDirectoriesInDomain are no longer used
    3. Instead use URL and FileManager
    4. NSSearchPathForDirectoriesInDomain is not needed
    5. Instead use FileManager.default.urls

    Here is a code sample to verify if a file named "database.sqlite" exists in application document directory:

    func findIfSqliteDBExists(){
    
        let docsDir     : URL       = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let dbPath      : URL       = docsDir.appendingPathComponent("database.sqlite")
        let strDBPath   : String    = dbPath.path
        let fileManager : FileManager   = FileManager.default
    
        if fileManager.fileExists(atPath:strDBPath){
            print("An sqlite database exists at this path :: \(strDBPath)")
        }else{
            print("SQLite NOT Found at :: \(strDBPath)")
        }
    
    }
    
    0 讨论(0)
  • 2020-11-28 21:43

    Check the below code:

    Swift 1.2

    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    
    let getImagePath = paths.stringByAppendingPathComponent("SavedFile.jpg")
    
    let checkValidation = NSFileManager.defaultManager()
    
    if (checkValidation.fileExistsAtPath(getImagePath))
    {
        println("FILE AVAILABLE");
    }
    else
    {
        println("FILE NOT AVAILABLE");
    }
    

    Swift 2.0

    let paths = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
    let getImagePath = paths.URLByAppendingPathComponent("SavedFile.jpg")
    
    let checkValidation = NSFileManager.defaultManager()
    
    if (checkValidation.fileExistsAtPath("\(getImagePath)"))
    {
        print("FILE AVAILABLE");
    }
    else
    {
        print("FILE NOT AVAILABLE");
    }
    
    0 讨论(0)
提交回复
热议问题