簡體   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