Read File Content Example in Swift

In this short tutorial, you will learn how to read from a file in Swift. The Swift code example below will cover the following:

  • Find a Documents directory on the device in Swift,
  • Read file content,
let fileName = "myFileName.txt"
var filePath = ""

// Fine documents directory on device
let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
       
if dirs.count > 0 {
    let dir = dirs[0] //documents directory
    filePath = dir.appending("/" + fileName)
    print("Local path = \(filePath)")
} else {
    print("Could not find local directory to store file")
    return
}

// Read file content. Example in Swift
do {
    // Read file content
    let contentFromFile = try NSString(contentsOfFile: filePath, encoding: String.Encoding.utf8.rawValue)
    print(contentFromFile)
}
catch let error as NSError {
    print("An error took place: \(error)")
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published. Required fields are marked *