Member-only story

iOS FileManager in Swift.

Mr.Javed Multani
2 min readOct 30, 2019

--

By using file manager we can perform operations like create,read,write,copy file etc.

We will see these all operations one by one by using file manager in swift.

Create Directory:

//create directory
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
let logsPath = documentsPath.appendingPathComponent(“data”)
print(logsPath!)

do{
try FileManager.default.createDirectory(atPath: logsPath!.path, withIntermediateDirectories: true, attributes: nil)

}catch let error as NSError{
print(“Unable to create directory”,error)
}

Write in File:

let file = “file1.txt”
let text = “some 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{
print(“cant write…”)
}
}

Read file:

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first{
let file = “file1.txt”
let fileURL = dir.appendingPathComponent(file)

//reading

do{
let text = try String(contentsOf: fileURL

--

--

Mr.Javed Multani
Mr.Javed Multani

Written by Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer

Responses (1)