NSFileManager.defaultManager().fileExistsAtPath returns false instead of true

前端 未结 2 444
天涯浪人
天涯浪人 2020-11-22 16:44

How is it possible?

let exists = NSFileManager.defaultManager().fileExistsAtPath(path.absoluteString)
print(\"exists: \\(exists)\") //false

相关标签:
2条回答
  • 2020-11-22 17:16

    (The code in this answer has been updated for Swift 3 and later.)

    Apparently your path variable is a NSURL (describing a file path). To get the path as a string, use the path property, not absoluteString:

    let exists = FileManager.default.fileExists(atPath: path.path)
    

    absoluteString returns the URL in a string format, including the file: scheme etc.

    Example:

    let url = URL(fileURLWithPath: "/path/to/foo.txt")
    
    // This is what you did:
    print(url.absoluteString)
    // Output:    file:///path/to/foo.txt
    
    // This is what you want:
    print(url.path)
    // Output:    /path/to/foo.txt
    
    0 讨论(0)
  • 2020-11-22 17:19

    If you want to check if a path exist,you should check path

    let url = NSURL(string: "balabala")
    
    let path = url?.path
    //Check path
    
    0 讨论(0)
提交回复
热议问题