Uiimage(Contentsoffile:) Returning Nil Despite File Existing in Caches Directory

UIImage(contentsOfFile:) returning nil despite file existing in caches directory

The problem there is that you are using URL property absoluteString where you should be using the path property. The difference between absoluteString and path properties is that absoluteString includes the file url scheme ("file://") which is the reason it doesn't find the file at what was supposed to be its path but it is actually its absoluteString.

iOS / Swift failing to write file as treating file path as directory path

URL(fileURLWithPath together with absoluteString is wrong.

You would have to write (note the different URL initializer):

let imgPath = URL(string: documentDirectoryPath.appendingPathComponent("studioframe\(savedImageCount).jpg").absoluteString)

but this (URLStringURL) is very cumbersome, there is a much simpler solution, please consider the difference between (string) path and URL

let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! // the Documents directory is guaranteed to exist.
let imgURL = documentDirectoryURL.appendingPathComponent("studioframe\(savedImageCount).jpg")
...
try data.write(to: imgURL, options: .atomic)

The file “xxx” couldn’t be opened because there is no such file

Your path variable is an URL, and path.absoluteString returns
a string representation of the URL (in your case the string
"file:///Users/Username/Documents/xxx.txt"), not the underlying file path
"/Users/Username/Documents/xxx.txt".

Using path.path is a possible solution:

let path = ... // some URL
let contentString = try String(contentsOfFile: path.path)

but the better method is to avoid the conversion and use the URL-based
methods:

let path = ... // some URL
let contentString = try String(contentsOf: path)

The folder 'Documents' doesn't exist error in Swift

You should use dir.path in order to convert the URL to a file path:

let files = try fileManager.contentsOfDirectory(atPath: dir.path)

NSKeyedUnarchiver.unarchiveObject not working

Both unarchiveObject(withFile and archiveRootObject(_:toFile expect a file path without the file:// scheme, so it's in both cases

url.path

rather than url.absoluteString

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

(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


Related Topics



Leave a reply



Submit