Swift - App Crashes when try to get JSON values for the second time

I am trying to get an array of values from a JSON file using Swift. I found the way to get the values printed when a button is pressed using a IBAction method.

The Function is printing the array fine the first time the button is pressed however, if I press the button again the app crashes giving the error:

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

The array that I get the first time from printing jsonResult looks Like:


1: {
        Age = 30;
        Email = "info@example.com";
        Location = Rome;
        MyText = "Design Agency";
        Name = Admin;
        Password = 123456;
        REF = 002;
        "Reg_Date" = "2015-07-28";
        *** = Male;
        Surname = "Mobile App"; }
2: {
        Age = 30;
        Email = "example@gmail.com";
        Location = London;
        MyText = "aaaaaaaaa";
        Name = Andrew;
        Password = 123456;
        REF = 001;
        "Reg_Date" = "2015-07-28";
        *** = Male;
        Surname = Nos; }


It seems that the second time I call the function, it cannot read the file anymore. Whats wrong with my code? Do I need to close the connection?


@IBAction func login_button(sender: AnyObject) {

            searchFunction()
        }


        func searchFunction() {
            var tempUrlValue = loginJsonResults.stringForKey("loginJsonResults")
            let urlPath: String = "https://example.com/iOS/users_result.json"
            var url: NSURL = NSURL(string: urlPath)!
            var request: NSURLRequest = NSURLRequest(URL: url)
            var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
            connection.start()

        }


        func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
        self.data.appendData(data)
    }


    func connectionDidFinishLoading(connection: NSURLConnection!) {
        var err: NSError
        var jsonResult: NSMutableArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSMutableArray

    //Call jsonResult Values
        var temporaryString: AnyObject = jsonResult[1]

        for (index, jsonResult) in enumerate(jsonResult){
            println("\(index + 1): \(jsonResult)")
            countUsers++
        }
        println(countUsers)
    }

If you are running the network code again without clearing self.data, then the line "self.data.appendData(data)" will tack another copy onto the end. The result will not be a valid JSON structure. You should clear out self.data before starting a new fetch.


Once you've fixed that, you should be able to handle invalid JSON anyway if you're fetcing over the Internet, so now would be a good time to add some error handling in the case that the JSON fails to parse.

What junkpile said plus…

If you use NSURLSession for your networking, you can avoid the need for accumulating data manually by using one of its convenience APIs. This simplifies your code and gets you off the now-deprecated NSURLConnection API.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Swift - App Crashes when try to get JSON values for the second time
 
 
Q