Read data from file

 Problem

I have a file and want to read its data.



 Recipe


// Create a FileHandle instance

let file: NSFileHandle? = NSFileHandle(forReadingAtPath: "hello.swift")

if file != nil {
    // Read all the data
    let data = file?.readDataToEndOfFile()

    // Close the file
    file?.closeFile()

    // Convert our data to string
    let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
    print(str!)
}
else {
    print("Ooops! Something went wrong!")
}

				

Heard the news?

The Swift Cookbook for Swift 3 is at last here! For iBooks, Kindle and Paperback.
Hurry up - and Check it out! ;-)

 

 Playground