FileManager.default.removeItem not removing file [duplicate] - ios

This question already has answers here:
Objc save a file to the tmp/ with URL it is not working
(1 answer)
UIImage(contentsOfFile:) returning nil despite file existing in caches directory [duplicate]
(1 answer)
NSURL path vs absoluteString
(3 answers)
Closed 5 years ago.
I'm trying to remove a file from the documents directory using FileManager.default.removeItem but is not deleting the file on the simulator. Here is my code:
if let dir = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
do {
let path = dir.appendingPathComponent(file).absoluteString
do {
try FileManager.default.removeItem(atPath:path)
} catch {
print(error)
}
}
}
But I always fails. Any of you knows why it fails?

You can write like this:
var filemanager = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString
let destinationPath = documentsPath.appendingPathComponent("Filename.jpg")
try! filemanager.removeItem(atPath: destinationPath)

absoluteString is the wrong API, the correct property for the file:// scheme is path.
The best solution is to use the URL related API
let fileURL = dir.appendingPathComponent(file)
...
try FileManager.default.removeItem(at: fileURL)

Related

iOS Swift : routing NSLog calls to file

is it possible to route all the NSLog calls from our iOS app and private frameworks into a single file easily.
Like redefining NSLog to something else ?
I translated this answer to Swift for you. Call this function in your didFinishLaunchingWithOptions in AppDelegate.
func redirectConsoleLogToDocumentFolder() {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).map(\.path)
let documentsDirectory = paths[0]
let logPath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("console.log").path
freopen(logPath, "a+", stderr)
}
This is the path to the console.log file on iOS devices: /var/mobile/Containers/Data/Application/<your-app>/Documents/console.log

FileManager.default.fileExists says documents directory does not exist [duplicate]

This question already has answers here:
NSFileManager.defaultManager().fileExistsAtPath returns false instead of true
(2 answers)
Closed 4 years ago.
FileManager.default.contentsOfDirectory claims that the documents directory does not exist, even though it clearly does. I'm using Swift 4.2 on my actual iPhone SE running iOS 12.1.2
I am reading the contents of the downloads directory in my app using the following:
do {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let downloadedContents = try FileManager.default.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
print(downloadedContents)
} catch {
print("Error while enumerating contents: \(error.localizedDescription)")
}
This prints the following, telling me that a file exists in the documents directory:
[file:///private/var/mobile/Containers/Data/Application/698F8D51-92AF-4BAB-A212-0A0982090550/Documents/example-file/]
(I moved the file there from the caches directory after downloading an in-app purchase, but I don't think that's relevant to this question).
Later in my code, I want to check if the file was downloaded. I'm using the following:
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let path = URL(fileURLWithPath: "example-file", relativeTo: documentsURL)
var isDir : ObjCBool = false
if FileManager.default.fileExists(atPath: path.standardizedFileURL.absoluteString, isDirectory: &isDir) {
if isDir.boolValue {
return true
} else {
return false // file exists but is not directory
}
} else {
return false // file does not exist at all
}
But this always returns false, even though contentsOfDirectory showed it exists.
While debugging, I also tried:
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
po FileManager.default.fileExists(atPath: documentsURL.standardizedFileURL.absoluteString)
But this, too, returns false. Now I'm pretty sure I'm just using the fileExists methods incorrectly.
Can anyone spot what I'm doing wrong?
Turns out one should use documentsURL.path, instead of any sort of URL.
The path begins with /var/mobile... whereas the URLs begin with file:///var...

iOS / Swift failing to write file as treating file path as directory path [duplicate]

This question already has an answer here:
UIImage(contentsOfFile:) returning nil despite file existing in caches directory [duplicate]
(1 answer)
Closed 4 years ago.
I have the following swift function that I hoped would save incoming bytes to a JPEG file on iOS. Unfortunately an exception is thrown by the call to data.write and I get the error message
The folder “studioframe0.jpg” doesn’t exist. writing to file:/var/mobile/Containers/Data/Application/2A504F84-E8B7-42F8-B8C3-3D0A53C1E11A/Documents/studioframe0.jpg -- file:///
Why does iOS think it is a directory path to a directory which does not exist as opposed to a file that I am asking it to write?
func saveToFile(data: Data){
if savedImageCount < 10 {
guard let documentDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
return
}
let imgPath = URL(fileURLWithPath: documentDirectoryPath.appendingPathComponent("studioframe\(savedImageCount).jpg").absoluteString)
savedImageCount += 1
do {
try data.write(to: imgPath, options: .atomic)
print("Saved \(imgPath) to disk")
} catch let error {
print("\(error.localizedDescription) writing to \(imgPath)")
}
}
}
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 (URL → String → URL) 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)

iOS - FileManager won't delete json file in document directory

I created a file in the document directory and for some reason when I try to delete it using the code below, it doesn't get deleted. The code doesn't throw any errors, but the file is still there
let fileManager = FileManager.default
if let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
let filePath = documentDirectory.appendingPathComponent("data.json")
do {
try fileManager.removeItem(atPath: filePath.path)
} catch let error as NSError {
print(error.localizedDescription)
}
}
I also tried to put it inside another folder and remove the folder but still the same problem.
This is the path where the file is stored :
Users/user1/Library/Developer/CoreSimulator/Devices/76AFDB69-75C8-464E-93F2-6ABF622068FD/data/Containers/Data/Application/7D268156-977A-4A3C-834B-6B13FA3DE76D/Documents/
you can try like below
if let filePath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("data.json"), fileManager.fileExists(atPath: filePath.path) {
do {
try fileManager.removeItem(atPath: filePath.path)
} catch let error as NSError {
print(error.localizedDescription)
}
}
The code doesn't throw any errors, but the file is still there
No, it isn't. The problem is with the way you are checking to see whether "the file is still there". You are looking on your computer for the file. But iOS files are sandboxed. At the time you are looking, the path where the file was is completely different from your claimed path:
Users/user1/Library/Developer/CoreSimulator/Devices/76AFDB69-75C8-464E-93F2-6ABF622068FD/data/Containers/Data/Application/7D268156-977A-4A3C-834B-6B13FA3DE76D/Documents/
Such paths are not permanent. They are meaningless and should not be used. The only way to know whether the file is still there is with more code from inside iOS, i.e. ask the FileManager. When you do, you will find that you are, indeed, deleting the file successfully.

loading data object from local file in Swift 3

I'm struggling to get an image file loaded in Swift 3.
Here is the code:
do {
let imageData = try Data(contentsOf: imageUrl2.asURL())
} catch {
print ("loading image file error")
}
And the current Url String is:
file:///Users/veikoherne/Library/Developer/CoreSimulator/Devices/889A08D5-B8CC-458C-99FF-643A4BA1A806/data/Containers/Data/Application/F64ED326-7894-4EE7-AA3B-B1BB10DF8259/Documents/img2017-03-23 17:39:24.jpg
and obviously I have checked that this file exists and is valid image. It always ends up telling me "loading image file error". Anyone have experiences loading local data in Swift 3?
The answer mentioned was using NSData object and probably Swift 2. Current Swift 3 refuses to bridge NSData to Data, that's why I have to use Data.
Loading data from local file you should use "contentsOfFile:" method.
Reference link: https://www.hackingwithswift.com/example-code/strings/how-to-load-a-string-from-a-file-in-your-bundle
So in case of reading data you can use:
Data(contentsOf: <URL>, options: <Data.ReadingOptions>)
Reading a plain text as a String, use:
String(contentsOfFile: <LocalFileDirPath>)
Reading an image from document directory, use:
UIImage(contentsOfFile: <LocalFileDirPath>)
Hope this would be helpful!
I experienced the same issue when trying to retrieve a file that I just downloaded. If you have saved a file from some url like I did, this should work:
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let localUrl = documentDirectory.appendingPathComponent("somefile.txt")
if FileManager.default.fileExists(atPath: localUrl.path){
if let cert = NSData(contentsOfFile: localUrl.path) {
return cert as Data
}
}
Swift 5 version.
func loadFileFromLocalPath(_ localFilePath: String) ->Data? {
return try? Data(contentsOf: URL(fileURLWithPath: localFilePath))
}

Resources