Read Data from file in Swift

October 15, 2017

In this example you can read data from a file in your iOS device

let home = FileManager.default.homeDirectoryForCurrentUser
let playgroundPath = "Documents/dev/xcode/DatePicker/c"

// Get your playground URL
let playgroundURL = home.appendingPathComponent(playgroundPath)

let newFile = playgroundURL.appendingPathComponent("test.txt").path

let fileHandle: FileHandle? = FileHandle(forReadingAtPath: newFile)

if fileHandle != nil {
    // Read data from the file
     let data = fileHandle?.readDataToEndOfFile()
   
     // Close the file
     fileHandle?.closeFile()
     // data to string conversion
     let text = String(data: data!, encoding: String.Encoding.utf8) as String!
     print(text ?? "")
}
else {
    print("Ooops! Something went wrong!")
}