简体   繁体   中英

“fatal error: unexpectedly found nil while unwrapping an Optional value” when parsing JSON

Note: I would like to know the reason of downvote. I think it's pretty legit question with proper format. I don't really care about votes since I'm only here for learning but whoever is giving the downvote without explanation is discouraging a lot of people to ask and learn.

I wrote below code for getting json from a webservice, which works fine when I run it in a new "single view project" but it gives **fatal error: unexpectedly found nil while unwrapping an Optional value** error when I add it in my project. You can also see where it goes wrong from below screenshot.

在此处输入图片说明

Code:

import UIKit

class NewsViewController: UIViewController {
    @IBOutlet var newsTableView: UITableView!

    var newsTitles : NSMutableArray = NSMutableArray() // will contain news contents from API
    var newsURLs : NSMutableArray = NSMutableArray()     // will contain news URLs from API
    var newsResponse : NSMutableArray = NSMutableArray() // will contain server response

    override func viewDidLoad() {
        super.viewDidLoad()

        getNews()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    // Calling News Service
    func getNews(){

        var serviceParam: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("key4news")!
        var apiURL = "http://myIP/myWebService?search_text=\(serviceParam)"
        println(apiURL)
        var request : NSMutableURLRequest = NSMutableURLRequest()
        request.URL = NSURL(string: apiURL)
        request.HTTPMethod = "GET"

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in


            var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
            let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

            if (jsonResult != nil) {

                self.newsResponse = jsonResult.objectForKey("result") as NSMutableArray

                for var i=0; i<self.newsResponse.count; i++ {
                    self.newsTitles[i] = self.newsResponse[i].objectForKey("title")! as NSString
                    self.newsURLs[i] = self.newsResponse[i].objectForKey("link")! as NSString
                    println("news title: \(self.newsTitles[i])")
                    println("news link: \(self.newsURLs[i])")
                    println("\n\n")
                }

            } else {
                // couldn't load JSON, look at error
                println("jsonResult is nil")
            }
        })
    }

    func tableView(tableView:UITableView!, numberOfRowsInSection section:Int) -> Int
    {
        return 10
    }

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
    {
        let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "newsItem")
        cell.textLabel?.text = newsTitles[indexPath.row] as NSString

        return cell
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("you've touched tableviewcell")
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
}

And this is my webservice's JSON format (it returns max 10 items in 'result' array):

{
  "status": "ok",
  "result": [
    {
      "date added": "2014-12-29 00:00:00",
      "link": "http:link3.com",
      "description": "description of first news",
      "title": "title of first news"
    },
    {
      "date added": "2013-10-15 00:00:00",
      "link": "http:link3.com",
      "description": "description of second news",
      "title": "title of second news"
    },
    {
      "date added": "2013-04-09 00:00:00",
      "link": "http:link3.com",
      "description": "description of third news",
      "title": "title of third news"
    }
  ]
}

How can I fix this?

I think you are not getting data from server in response and that's why getting this error.

You need to do url encoding.

YOUR CODE

var serviceParam: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("key4news")!
var apiURL = "http://myIP/myWebService?search_text=\(serviceParam)"

Need to be like

var serviceParam: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("key4news")!        
serviceParam = serviceParam.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
var apiURL = "http://myIP/myWebService?search_text=\(serviceParam)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM