How to write, read and delete file in ios
This post introduce file I/O in iOS.
Let's study how to write, read and delte file in iOS.
1. File Manager
lazy var fileManager = {
return FileManager.default
}()
To deal with File I/O, we need FileManager class.
FileManager class is convenient interface to the contents of the file system.
2. Variety of Directory in iOS
lazy var desktopDirectory = {
return fileManager.urls(for: .desktopDirectory, in: .userDomainMask).first
}()
lazy var documentDirectory = {
return fileManager.urls(for: .documentDirectory, in: .userDomainMask).first
}()
lazy var libraryDirectory = {
return fileManager.urls(for: .libraryDirectory, in: .userDomainMask).first
}()
lazy var userDirectory = {
return fileManager.urls(for: .userDirectory, in: .userDomainMask).first
}()
lazy var downloadDirectory = {
return fileManager.urls(for: .downloadsDirectory, in: .userDomainMask).first
}()
lazy var trashDirectory = {
return fileManager.urls(for: .trashDirectory, in: .userDomainMask).first
}()
There are diverse directory to deal with file in iOS.
3. Writing
do {
let fileName = "testFile.txt" //1
guard let filePath = documentDirectory?.appendingPathComponent(fileName) else { return }
print("filePath: \(filePath.absoluteString)")
let data = "Hello World!"
try data.write(to: filePath, atomically: false, encoding: .utf8) //2
} catch let error {
print("write error : \(error.localizedDescription)")
}
1 => This is file name.
2 => Write this file. The parameter of atomically dictates whether you write auxiliary file.
If false, the file system write file directly to path.
If true, the file system write auxiliary file and then it is renamed to path.
4. Reading
do {
let fileName = "testFile.txt"
guard let filePath = documentDirectory?.appendingPathComponent(fileName) else { return }
print("filePath: \(filePath.absoluteString)")
let data = try String(contentsOf: filePath, encoding: .utf8) //1
contentLabel.text = data
} catch let error {
print("read error : \(error.localizedDescription)")
}
1 => Produces a string created by reading data from a given URL.
5. Deleting
do {
let fileName = "testFile.txt"
guard let filePath = documentDirectory?.appendingPathComponent(fileName) else { return }
print("filePath: \(filePath.absoluteString)")
try fileManager.removeItem(at: filePath) //1
} catch let error {
print("delete error : \(error.localizedDescription)")
}
1 => Delete file placed on this path.
The full code is in below Github url.
https://github.com/antwhale/SampleFileIO_ios