Search code examples
iosswiftuidocumentpickerviewcontroller

The file couldn't be opened because there is no such file when getting FileAttributesKey - Swift


I am trying to get the FileAttributesKey using FileManager in iOS using Swift. When I try that, I am getting the following error"

Error Domain=NSCocoaErrorDomain Code=260 "The file “Personal%20Narrative%20Essay.txt” couldn’t be opened because there is no such file." UserInfo={NSFilePath=file:///private/var/mobile/Library/Mobile%20Documents/com~apple~TextEdit/Documents/Personal%20Narrative%20Essay.txt, NSUnderlyingError=0x283e720a0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

It says that the file doesn't exist but I know that it does exist because it is appearing in the UIDocumentPicker and I am able to get the contents of the file using try! Data(contentsOf: URL).

My code for getting the attributes of the file is:

func processURL(url: URL) -> Bool {
        let newPath = url.absoluteString
        print(newPath)
        do {
            let attributes = try FileManager.default.attributesOfItem(atPath: newPath)
            let fileSize = attributes[FileAttributeKey.size]
            print("Calculated File Size: \(fileSize!)")
            return true
        }
        catch {
            print(error)
            self.isShowingSpinner = false
            self.isShowingURLErrorAlert = true
            return false
        }
        return true
    }

I just need to be able to get the file size for now which I am doing using the above function. I do not understand if I am doing something wrong. Thanks in advance for the help.


Solution

  • I could reproduce your issue with a simple Playground where I placed a resource called "hello.text".

    Here are the results:

    let filePath = Bundle.main.path(forResource: "hello", ofType: "txt")!
    // Prints as /var/folders/blah-blah-blah/hello.txt
    let fileURL = Bundle.main.url(forResource: "hello", withExtension: "txt")!
    // Prints as file:///var/folders/blah-blah-blah/hello.txt
    

    The issue is that the file:// prefix is specific to file's URL and is not expected for path arguments of type String.

    try FileManager.default.attributesOfItem(atPath: fileURL.absoluteString) // ❌
    try FileManager.default.attributesOfItem(atPath: fileURL.path) // ✅