Last Updated: February 25, 2016
· ghafran

Read File Contents - iOS & Swift

Use the code below to read the contents of a file in iOS using swift.

Remember, the path of the file is derived from NSBundle, it is not the relative path of file in your project.

func readFile(fileName: String, fileType: String) -> String{
    var fileRoot = NSBundle.mainBundle().pathForResource(fileName, ofType: fileType)
    var contents = NSString.stringWithContentsOfFile(fileRoot!, encoding: NSUTF8StringEncoding, error: nil)
    return contents

// example: read file.txt
var contents = readFile("file", fileType: "txt")