When you’re first getting started with Swift, even the easiest things may seem a challenge. For example, reading in a JSON file, converting its contents to a String and then sending the result to the console may take a while to figure out (at least, it did for me…).
I needed to do this in my current project for diagnostic purposes, and thought it might be helpful to others, so here’s the little code snippet I used:
// 1 let filePath = NSBundle.mainBundle().pathForResource("MyJSONFileName",ofType:"json") // 2 var readError:NSError? // 3 if let data = NSData(contentsOfFile:filePath!, options:NSDataReadingOptions.DataReadingUncached, error:&readError) { // 4 let stringData = NSString(data: data, encoding: NSUTF8StringEncoding) // 5 println("data read: \(stringData)") }
As you can see, it’s pretty straightforward.
- Create a file path to the file.
- Declare an NSError object for use in the reading (this example just eats the error, however).
- Read in the data from the JSON file.
- Create an NString object, initializing it with the NSString(data:encoding:) method.
- Output the result.