[英]“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. 我写了下面的代码,用于从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**
当我添加它时我的项目。 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): 这是我的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"
}
]
}
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)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.