I am trying to show a list of files from my computer using a server app that uses the IP address and you can look for a file from the phone.
I am fetching files successfully, but I have a problem with showing the size and creation date of files. This works fine on the iOS simulator!!! but on the real device, I am getting this error for each file:
FileAttribute error: Error Domain=NSCocoaErrorDomain Code=260 "The file “office-decor.jpg” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/username/Desktop/My%20office%20stuff/office-decor.jpg, NSUnderlyingError=0x281e279c0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
I have created an URL extension to show date, size:
extension URL {
var attributes: [FileAttributeKey : Any]? {
do {
return try FileManager.default.attributesOfItem(atPath: path)
} catch let error as NSError {
print("FileAttribute error: \(error)")
}
return nil
}
var fileSize: UInt64 {
return attributes?[.size] as? UInt64 ?? UInt64(0)
}
var fileSizeString: String {
return ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file)
}
var creationDate: Date? {
return attributes?[.creationDate] as? Date
}
}
my file path is something like this:
Users/username/Desktop/xxx.jpg
and trying to get the file path using URL like this to get the file size:
private var fileSize: String {
guard let url = URL(string: path.addURLEncoding()) else { return "-" }
return url.fileSizeString
}
extension String {
func addURLEncoding() -> String {
return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
}
}
I also tried file://
and URL(filePath...), URL(fileURLWithPath
but still get that error on the device, which is working totally fine on simulator. Any idea how to fix that?