NSFileManager.defaultManager().fileExistsAtPath returns false instead of true
Asked Answered
D

3

56

How is it possible?

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

This is path.absoluteString

//file:///Users/kuna/Library/Developer/CoreSimulator/Devices/92BD140D-5C14-43C4-80D6-904BB9594ED6/data/Containers/Data/Application/5B818832-BB19-4047-A7F8-1487F36868D6/Documents/wishlists/68/147/128/IMG_0006.PNG

And you can see it is there where it should be:

enter image description here

What is going on?

Dillingham answered 7/12, 2015 at 13:56 Comment(2)
can you print the document directory func printDocument() { let pathToFile = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.CachesDirectory , .UserDomainMask, true)[0] do { let namesOfFile = try Manager.contentsOfDirectoryAtPath(pathToFile) for name in namesOfFile { print("name : (name)") } }catch let error as NSError { print("print : (error)") } }Outlook
so apparently the file does not exist . How do you Save itOutlook
S
142

(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
Sturges answered 7/12, 2015 at 14:2 Comment(2)
It worked, what is the difference since it is completely the same when I print it?Beene
@BartłomiejSemańczyk the difference is absoluteString also includes file:// like this: file:///Users/kuna/..., path just returns /Users/kuna/...Homily
B
5

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

let url = NSURL(string: "balabala")

let path = url?.path
//Check path
Bleed answered 7/12, 2015 at 14:2 Comment(1)
This is the right answer and you got +1 but you should be more clear. if (FileManager.default.fileExists(atPath: url?.path.path))Bazan
A
4

FileManager extension that allows to check if file exists using URL, supports changes in iOS 16:

import Foundation

extension FileManager {
    func fileExists(atURL url: URL) -> Bool {
        var path: String
        if #available(iOS 16.0, *) {
            path = url.path(percentEncoded: false)
        } else {
            path = url.path
        }

        return FileManager.default.fileExists(atPath: path)
    }
}

How to use:

let exists = FileManager.default.fileExists(atURL: url)
Avelar answered 17/3, 2023 at 5:22 Comment(2)
Your answer saves my time! Than you!Bandylegged
thank you, I was missing the percentEncoded: false part, makes a lot of sense!Saponaceous

© 2022 - 2024 — McMap. All rights reserved.