【发布时间】:2016-05-13 09:45:04
【问题描述】:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func onbutton(sender: UIButton) {
inputarea.text = "Success"
getweatherdata("http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98")
// UIApplication.sharedApplication().openURL(NSURL(string:"http://www.reddit.com/")!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getweatherdata(urlString : String){
let url = NSURL(string: urlString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in dispatch_async(dispatch_get_main_queue(),{
self.setLabels(data!)
})
}
task.resume()
}
我正在尝试实现一个简单的天气应用程序,我能够编译代码,但一旦执行后,我在函数调用 self 处遇到错误“线程 1:exc_bad_instruction(code=exc_i386_invop,subcode=0x0) 错误” .setLabels(data!),我检查了 url,它返回的数据不是 nil。
我有函数 setLabels 提取儿子数据并显示它,如果有人需要,我很乐意提供整个代码。谢谢
请找到下面的 setLabels 函数,appname 和 templ 是 View 中的标签
func setLabels(weatherdata: NSData){
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(weatherdata, options: []) as? NSDictionary {
print(jsonResult)
if let name = jsonResult["name"] as? String{
appname.text = name
}
if let main = jsonResult["main"] as? String{
//if let temp = main["temp"] as? Double {
//templ.text = String(format: "%.1f",temp)
templ.text = main
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
【问题讨论】:
标签: ios swift exception optional