nmuvxw
Last Updated: September 15, 2016
·
21.54K
· aladine
Ac36fd1db0498ad7ff61442fe5f9d721

Read a file in Swift

To read content of a file in Swift, simply specify the name and type in this snippet:

var data :NSData? = FileUtility.dataFromPath("data") as? NSData
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "json")
let content = NSString.stringWithContentsOfFile(path) as String
println(content) // prints the content of data.json

1 Response
Add your response

16181
Speechrocket4 square

The first line doesn't do anything in this example and stringWithContentsOfFile is deprecated. To print the string, you'd do this:

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "json")
var error:NSError?
if let content = NSString.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: &error) {
println(content) // prints the content of data.json
}

but if you wanted to transform the JSON into data you'd do something like this:

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "json")
var error:NSError?
var data:NSData = NSData(contentsOfFile: path)
let json:AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error:&error)
 // JSONObjectWithData returns AnyObject so the first thing to do is to downcast this to a known type
if let nsDictionaryObject = json as? NSDictionary {
        if let swiftDictionary = nsDictionaryObject as Dictionary? {
            println(swiftDictionary)
    }
}
else if let nsArrayObject = json as? NSArray {
       if let swiftArray = nsArrayObject as Array? {
           println(swiftArray)
      }
 }

However, downcasting to a dictionary or an array doesn't transform all nested content into Swift instances and so it is a process that will need to be repeated. Hence the Swift/JSON discussions and GitHub postings that have been going on.

over 1 year ago ·