“致命错误:在解析JSON时意外地在解包可选值时发现nil”

时间:2015-03-27 12:48:01

标签: json swift

注意:我想知道downvote的原因。我认为这是一个非常合理的问题,格式正确。我并不真正关心选票,因为我只是在这里学习,但是没有任何解释而给予downvote的人会阻止很多人提问和学习。

我在下面写了一个从webservice获取json的代码,当我在一个新的单一视图项目中运行它时工作正常#34;但是当我在项目中添加它时,它会出现**fatal error: unexpectedly found nil while unwrapping an Optional value**错误。您还可以从下面的屏幕截图中看到它出错的地方。

enter image description here

代码:

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.
    }
}

这是我的网络服务的JSON格式(它返回&#39;结果&#39;数组中的最多10个项目):

{
  "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"
    }
  ]
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

我认为您没有从服务器获取数据作为响应,这就是导致此错误的原因。

您需要进行网址编码。

您的代码

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

需要像

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