Last Updated: September 29, 2021
·
65.03K
· aladine

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

Related protips:

Some simple Swift Extensions (Strip HTML, RGB Color, Color invert, Dismiss modal segue)

1 Response
Add your response

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 ·