繁体   English   中英

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

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

注意:我想知道拒绝投票的原因。 我认为使用适当的格式是个很合法的问题。 我并不真的在乎选票,因为我只是在这里学习,但是谁在不加解释的情况下给出弃权票,则会阻止很多人去问和学习。

我写了下面的代码,用于从Web服务获取json,当我在新的“单视图项目”中运行json时,效果很好,但它给出了**fatal error: unexpectedly found nil while unwrapping an Optional value**在添加**fatal error: unexpectedly found nil while unwrapping an Optional value****fatal error: unexpectedly found nil while unwrapping an Optional value**当我添加它时我的项目。 您还可以从下面的屏幕截图中查看出了问题所在。

在此处输入图片说明

码:

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

这是我的Web服务的JSON格式(它在“结果”数组中最多返回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"
    }
  ]
}

我怎样才能解决这个问题?

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

您需要进行网址编码。

您的密码

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)"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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