Able to write/read file but unable to delete file SWIFT
Your fullPath
variable is a (optional) URL
. To convert that to a file path string, use the .path
property, not string interpolation:
fileManager.removeItem(atPath: fullPath!.path)
Or better, use the URL directly without converting it to a path:
fileManager.removeItem(at: fullPath!)
(And get rid of the forced unwrapping in favor of option binding ... :-)
Delete files in iOS directory using Swift
I believe your problem is on this line:
let filePaths = try fileManager.contentsOfDirectoryAtPath("\(documentsUrl)")
You're using contentsOfDirectoryAtPath()
with something that is an NSURL
. You choose either path strings or URLs, not try to mix them both. To pre-empty your possible next question, URLs are preferred. Try using contentsOfDirectoryAtURL()
and removeItemAtURL()
.
Another curious thing you should look at once you resolve the above: why are you using NSTemporaryDirectory()
for the file path when you try to delete? You're reading the document directory and should use that.
Deleting contents of text file
Simply write an empty string to the file like this:
let text = ""
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
Delete a file selected by user from Files Directory in Swift 4?
you need to create file path by appending filename to base url for your directory
func delete(fileName : String)->Bool{
let fileManager = FileManager.default
let docDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let filePath = docDir.appendingPathComponent(fileName)
do {
try FileManager.default.removeItem(at: filePath)
print("File deleted")
return true
}
catch {
print("Error")
}
return false
}
Why can't I delete this file from my Xcode project?
Some options
- Restart Xcode
- Clean project, Product—>Clean
- Put the file back and delete it from Xcode
Why can't I delete files from my XCode project?
That isn't how folder references work. The idea is that its only a reference, you can open files within it and save it from those editors, you can delete or move the entire reference throughout the xcode project, but you can't actually edit it - its read only as far as xcode is concerned. Likewise, you cannot restructure it (move internal files around).
I'm not to sure why apple decided to make this the case, but apparently they have.
If you want to know how one might use the xcode folder system, here's how I tend to use them with my projects:
Whenever I subdivide code into folders, when I drag them into my project I click "recursively create groups for any added folders". If you do this, you any changes you make within xcode will not reflect the actual file itself. As far as I know, there is no way to do this. What does happen then is that when you add a new code file to it, the directory starts off in that file by default. ie, you don't need to navigate to it manually when you create a new file.
I use folder references whenever I'm working with content for an application I'm using. This way, I add all my images, folders, configuration files, whatever - and xcode immediately lists them. The reason I have it within xcode, I can I copy the files into the executables directory by dragging the folder reference into a "Copy Files" build phase.
Thats basically (to my knowledge) how one uses the folder types within xcode - sadly, I don't know how to achieve the functionality you want. You may have to manually delete the folders in finder, which if you do use folder references will update xcode to the change.
Deleting file from shared app group
Here is some code snippet of my emoji app.
It works well.
func removeImage(itemName: String, fileExtension: String) {
let fileName:String = itemName + "." + fileExtension
let fileManager = FileManager.default
guard let groupURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.io.XXXXXX.XXXX") else {
return
}
let storagePathUrl = groupURL.appendingPathComponent("image/" + fileName, isDirectory: false)
let storagePath = storagePathUrl.path
do {
if fileManager.fileExists(atPath: storagePath) {
try fileManager.removeItem(atPath: storagePath)
}
} catch let error as NSError {
print(error.debugDescription)
}
}
"image" is just the name of sub folder of app group.
If you are saving files directly in the root folder, you can remove it.
Hope it helps you.
Vapor Swift How to delete files collected from fileIO
This is a function I use:
func deleteFile(_ filename: String) throws {
let filepath = try workingDirectoryURL(with: ["folder/of/files", filename]).path
try FileManager.default.removeItem(atPath: filepath)
}
Build the path from the project's base folder.
Read and write a String from text file
For reading and writing you should use a location that is writeable, for example documents directory. The following code shows how to read and write a simple string. You can test it on a playground.
Swift 3.x - 5.x
let file = "file.txt" //this is the file. we will write to and read from it
let text = "some text" //just a text
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */}
//reading
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {/* error handling here */}
}
Swift 2.2
let file = "file.txt" //this is the file. we will write to and read from it
let text = "some text" //just a text
if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)
//writing
do {
try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
//reading
do {
let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
}
Swift 1.x
let file = "file.txt"
if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
let dir = dirs[0] //documents directory
let path = dir.stringByAppendingPathComponent(file);
let text = "some text"
//writing
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
//reading
let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
}
Related Topics
Pause an Skaction in Spritekit with Swift
How to Take Screen Shot Programmatically (Swift, Spritekit)
How to Check If 'Any(Not Any)' Is Nil or Not in Swift
Resize a Sklabelnode Font Size to Fit
Swiftui Onhover Doesn't Register Mouse Leaving the Element If Mouse Moves Too Fast
Does Swift Have an Implicit Object Initializer, Like in C#
How to Open Another Window in MACos in Swift with Cocoa
What Is the Backslash(\) Used for in Swiftui
Navigationview Doesn't Display Correctly When Using Tabview in Swiftui
How to Make Alphabetically Section Headers in Table View with a Mutable Data Source
How to Connect Aksequencer to a Akcallbackinstrument
Avspeechutterance - Swift - Initializing with a Phrase
Swiftui - Foreach Deletion Transition Always Applied to Last Item Only
"Cannot Inherit from Non-Open Class" Swift
How to Animate Transition Between Views in Swiftui
How to Get the Realy Fixed Device-Id in Swift