Getting FileAttribute error for files stored on my Mac - ios

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?

Related

Resolved URL bookmark (iCloud file) stops working after a few days: no such file or directory

I'm reading a file using UIDocumentPickerViewController:
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let url = urls.first else {
return
}
openDocument(at: url) { result in
if let .success(data) = result {
save(url)
}
}
}
func openDocument(at url: URL, completion: (Result<Data, LoadError>) -> Void) {
if startAccessingSecurityScopedResource() {
defer { stopAccessingSecurityScopedResource() }
do {
let data = try Data(contentsOf: self)
return .success(data)
} catch {
return .failure(.genericError(error))
}
}
return .failure(.noAccess)
}
So after reading the document I make a copy of the bookmarkData of its URL:
func save(_ url: URL) {
NSFileCoordinator().coordinate(readingItemAt: url, error: &error) { coorindatedURL in
if coorindatedURL.startAccessingSecurityScopedResource() {
defer { coorindatedURL.stopAccessingSecurityScopedResource() }
do {
let bookmarkData = try coorindatedURL.bookmarkData()
// save bookmarkData with the url
} catch {
}
}
}
}
Then every time I read the document I read from saved bookmarkData:
var stale = false
if let url = try? URL(resolvingBookmarkData: bookmarkData, bookmarkDataIsStale: &stale), stale == false {
if startAccessingSecurityScopedResource() {
defer { stopAccessingSecurityScopedResource() }
do {
let data = try Data(contentsOf: url)
} catch {
}
}
}
It works at first, and for 1 or 2 days, but after a few days I started getting this error:
Error Domain=NSCocoaErrorDomain Code=260 "The file FILENAME couldn’t be opened because there is no such file." UserInfo={NSFilePath=/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/PATH/TO/FILE.doc, NSUnderlyingError=0x2830cae80 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
I checked the file is still there in my iCloud folder, and the stale flag is false. So I'm not sure what the problem is?
Thanks!

Firebase Storage Upload Error in Share Extensions

I'm creating an app with App Extension and I'm having trouble uploading files to firebase storage.
I choose a photo that I chose from the Photos application or another application for my own application by pressing the share button.
I am getting the URL of the selected photo in ShareViewController.
if let items = (self.extensionContext?.inputItems.first as? NSExtensionItem)?.attachments {
let contentType = kUTTypeData as String
for item in items {
item.loadItem(forTypeIdentifier: contentType, options: nil) { url, error in
if let path = url as? NSURL {
URLs.append(path.absoluteString!)
}
else {}
}
}
}
I'm trying to upload the URLs I get this way to firebase storage.
let uploadTask = riversRef.putFile(from: URLs[0], metadata: nil) { metadata, error in
guard let metadata = metadata else {
return
}
...
}
There is a problem with the URL of the selected photo but I can't quite understand it. I can get the size, name and other properties of the photo from the URL. I can even copy this photo to another directory with FileManager. I'm getting the URL from FileManager but still getting the same error. But when I try to install I get the following error.
Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown error occurred, please check the server response." UserInfo={bucket=appBucketName, _NSURLErrorFailingURLSessionTaskErrorKey=BackgroundUploadTask <9381D3C6-241C-4737-9589-BA5A7CFAF9E4>.<1>, object=PATH/6B36F026-CD6E-4E00-8A19-C530DC606674.jpg, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"BackgroundUploadTask <9381D3C6-241C-4737-9589-BA5A7CFAF9E4>.<1>"
), NSLocalizedDescription=An unknown error occurred, please check the server response., ResponseErrorDomain=NSURLErrorDomain, ResponseErrorCode=-995}
Solutions I tried;
I will not use putData.
I tried App Groups. I already have the URL of the file. I need to install directly but it doesn't work.
extension FileManager {
func documentsDirectory() -> URL {
let path = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.name")
return path!
}
func uploadPath(srcURL: URL, name: String, completion: #escaping ((_ filePath: URL?) -> Void)) {
do {
let path = documentsDirectory().appendingPathComponent("tempory")
try FileManager.default.createDirectory(atPath: path.relativePath, withIntermediateDirectories: true, attributes: nil)
let fullPath = path.appendingPathComponent(name)
try FileManager.default.copyItem(at: srcURL, to: fullPath)
completion(fullPath)
}
catch {
completion(nil)
}
}
}
Note: I am using Firebase emulator and Xcode simulator. I don't have any problems with the main application.
If there is missing information or incorrect information, please warn, I will correct it. Thank you for your help in advance.

Problems deleting file in fileManager(FileManager.default.removeItem) while unit testing

Currently there are issues with files not being deleted. I've looked at other posts like: FileManager.default.removeItem not removing file [duplicate]
and Error deleting contents in directory - Domain=NSCocoaErrorDomain Code=4 | Domain=NSPOSIXErrorDomain Code=2 “No such file or directory”
I'm getting the same error “No such file or directory”. This is happening with this function when it's being unit tested:
internal func getCacheFolderPath() -> String {
var folderPath = ""
guard let path = self.urls(for:.cachesDirectory , in: .userDomainMask).last?.path else { return folderPath }
folderPath = path + "/NetworkCache"
if !self.fileExists(atPath: folderPath) {
do {
try self.createDirectory(atPath: folderPath, withIntermediateDirectories: false, attributes: nil)
}
catch {
print(error.localizedDescription)
}
}
return folderPath
}
internal func filePathForFileName(name: String) -> String {
let cyptoName = name.md5()
return getCacheFolderPath() + "/" + (cyptoName ?? "")
}
func deleteFile(forFile fileName: String){
let path = self.filePathForFileName(name: fileName)
if self.fileExists(atPath: path) {
do {
try self.removeItem(atPath: path)
// print(path)
} catch {
print(error.localizedDescription)
}
}
}
This is what the unit test looks like:
func test_deleteFile(){
let path = sut!.filePathForFileName(name: fileName)
sut?.deleteFile(forFile: fileName)
print(path)
if sut!.fileExists(atPath: path){
let filemanager = FileManager.default
do {
try filemanager.removeItem(atPath: path)
} catch {
print ("The file could not be removed: \(error)")
}
}
}
FYI I am using a mockFileSystem that is subclassed from FileManager. Even when I try and delete the path manually in the do, try, catch block it still returns the error “No such file or directory”.

Download fails when on first use or app goes in background

Alamofire 3.5.0, Swift2.2
I'm downloading ZIP files with the Alamofire download method, I've noticed that when I'm starting download process and apps goes background than the download fails with following error:
----------------------
error Optional(Error Domain=NSCocoaErrorDomain Code=4
"“CFNetworkDownload_pZ56nc.tmp” couldn’t be moved to “courses”
because either the former doesn't exist, or the folder containing
the latter doesn't exist." UserInfo=
{NSSourceFilePathErrorKey=
/private/var/mobile/Containers/Data/Application/[UUID]/tmp/CFNetworkDownload_pZ56nc.tmp,
NSUserStringVariant=(
Move
),
NSDestinationFilePath=
/var/mobile/Containers/Data/Application/[UUID]/Library/courses/course_302.zip,
NSFilePath=
/private/var/mobile/Containers/Data/Application/[UUID]/tmp/CFNetworkDownload_pZ56nc.tmp,
NSUnderlyingError=0x13f52f990 {Error Domain=NSPOSIXErrorDomain
Code=2 "No such file or directory"}})
----------------------
this is the code to download a file:
//...
var userLibraryPath:String = {
return NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0]
}()
//...
let _coursePath:NSURL = NSURL(string: "file://\(userLibraryPath)/)")!
//...
let zipURL = _coursePath.URLByAppendingPathComponent("course_\(courseId).zip")
//if file exists destroy it
if let zipPath = zipURL?.path where NSFileManager.defaultManager().fileExistsAtPath(zipPath) {
do {
try NSFileManager.defaultManager().removeItemAtPath(zipPath)
} catch let error as NSError {
print(error)
}
}
//
let downloadRequest = Alamofire.download(Router.download(courseId), destination: { (url:NSURL, urlResponse:NSHTTPURLResponse) -> NSURL in
//
return zipURL!
//
}).progress({ (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
//
let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
dispatch_async(GlobalMainQueue, {
self.notifyDownloadProgress(courseId, progress: progress)
})
}).response(completionHandler: { (request:NSURLRequest?, response:NSHTTPURLResponse?, data:NSData?, error:NSError?) in
self.removeFromQueue(courseId)
print("response")
print("----------------------")
print("error \(error)")
print("----------------------")
//here I would try to extract it
})
UPDATE I've just tested on iPhone 5 fresh install of the app and it doesn't have to go to background (e.g. via home button) to fail, it fails on the very first load (and any subsequent) untill after the app is killed and reopened.
Why is the "/private" bit added to the path? What am I doing wrong here?
And indeed it was a "No such file or directory" error.
When I've added:
//
let downloadRequest = Alamofire.download(Router.download(courseId), destination: { (url:NSURL, urlResponse:NSHTTPURLResponse) -> NSURL in
let course = zipURL!.URLByDeletingLastPathComponent!.path!
let fm = NSFileManager.defaultManager()
var isDir:ObjCBool = false
if(fm.fileExistsAtPath(path, isDirectory: &isDir) == false){
//doesnt exist
do {
try fm.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
//
print(error)
}
}
return zipURL!
//
})

iOS Dropbox get thumbnails images

I'm trying to load thumbnails images of a Dropbox account, but I got a bug. I create a local directory in the first method to put thumbnails, and I make a request to load them, but it doesn't works.
Here is my code :
// Create directory method
func createTempDirectory() -> String? {
let tempDirectoryTemplate = NSTemporaryDirectory()
tempDirectoryTemplate.stringByAppendingPathComponent("XXXXX")
let fileManager = NSFileManager.defaultManager()
var err: NSErrorPointer = nil
if fileManager.createDirectoryAtPath(tempDirectoryTemplate, withIntermediateDirectories: true, attributes: nil, error: err) {
return tempDirectoryTemplate
}
else {
return nil
}
}
// Get thumbnails images
func restClient(client: DBRestClient!, loadedMetadata metadata: DBMetadata!) {
temporaryDirectory = createTempDirectory()!
for file in metadata.contents {
if (file.thumbnailExists == true) {
client.loadThumbnail(file.path, ofSize: "s", intoPath: temporaryDirectory)
}
}
self.collectionView?.reloadData()
}
And this is the error :
[WARNING] DropboxSDK: error making request to /1/thumbnails/dropbox/star.jpg - (4) Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)
Thanks for your help !

Resources