0

hi guys I have a json file in my swift project and I want to read this file and use its content to draw stuff. I created a controller where I have the following.

import UIKit

class MapViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonData = getJSON("hls.json")

        println(jsonData)

        let jsonDataResult = parseJSON(jsonData)

        println("\(jsonDataResult)")
    }

    func getJSON(urlToRequest: String) -> NSData{
        return NSData(contentsOfURL: NSURL(string: urlToRequest)!)!
    }

    func parseJSON(inputData: NSData) -> NSDictionary{
        var error: NSError?
        var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary

        return boardsDictionary
    }
}

Unfortunately it says: fatal error: unexpectedly found nil while unwrapping an Optional value at the getJSOn function. I have the file called hls.json in my app directory where all my swift files are so I don't know if its because it can't read it or what.. Hope someone can help me out!

1
  • 1
    - first, verify the result of JSONObjectWithData is not nil. Then, remember that json string can be a dictionary or array. Commented Feb 5, 2015 at 21:44

2 Answers 2

1

I'm also new at this JSON stuff. However, I think I know what the problem is. You said you are trying to read the file called hls.json in your app directory, but looking at your getJSON function suggests that you're trying to grab the data from the internet.

(Correct me if I'm wrong) I believe what you're doing right now is trying to get the JSON data from a website called "hls.json" rather than trying to access a file in your computer.

Because a website with the url "hls.json" doesn't exist, calling getJSON("hls.json") will always return nil.

The way to solve this is to use

let filePath = NSBundle.mainBundle().pathForResource("hls",ofType:"json")

and then using

if let data = NSData(contentsOfFile:filePath!, options: NSDataReadingOptions.DataReadingUncached, error:&readError) { success(data: data) }

to act as the data you do for the parse JSON.

Hope that helps. Again, I'm also new at this so I'm not absolutely sure ;P

Sign up to request clarification or add additional context in comments.

Comments

1

You are force unwrapping a nil using exclamation marks in getJSON(). And this is because your NSURL might be nil due to the way its created.

You might need to change your getJSON() function to get the URL for your file correctly as follows:

func getJSON(fileName: String, extn: String) -> NSData?
{
    if let fileURL = NSBundle.mainBundle().URLForResource(fileName, withExtension: extn) {
        if let data = NSData(contentsOfURL: fileURL) {
            return data
        }
    }
    return nil
}

Note that this function may return nil. Hence the return signature is NSData?.

So you have to unwrap the NSData? coming out of getJSON function before you can call your parseJSON function, as parseJSON takes a non-optional NSData as the argument.

The unwrap can be done with another if let statement as follows:

override func viewDidLoad() {
    super.viewDidLoad()

    if let jsonData = getJSON("hls", "json") {
        println(jsonData)
        let jsonDataResult = parseJSON(jsonData)
        println("\(jsonDataResult)")
    }
}

Since the question is about the nil unwrapping error on getJSON(), I have not looked at the correctness of parseJSON() function.

9 Comments

Thanks! this works almost.. Just the parseJSON seems also to be broke.. I have that like this now if let jsonDataResult = parseJSON(jsonData!) { println("(jsonDataResult)") } and it says that the bound value in a conditional binding must be of optional type. So when I explicitly say let it be anyobject the error goes away but then the function parseJSON tells me the same error as the other function before..
Once you do if let jsonData = getJSON("hls", "json"), the conditional value returned from getJSON() is unwrapped into jsonData. This means you can not force-unwrap jsonData with an exclamation mark like in your previous comment. What happens when you change jsonData! to jsonData ?
It says value of optional type NSDATA? not unwrapped did you mean to use ! or ?
Can you be a bit more clear on which line exactly the error is on, and which variable? Since jsonData is a non-conditional, you can not use jsonData!, so the error is somewhere else.
This is how the error pops up when I add a question mark instead of the ! cl.ly/image/1M0x283Z1I1r
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.