gpt4 book ai didi

swift - NSURLSession:在展开可选值时意外发现 nil

转载 作者:行者123 更新时间:2023-11-28 09:37:11 27 4
gpt4 key购买 nike

我正在尝试从我自己的 API 取回数据。我可以在我的控制台日志中看到数据,但它一直给我 found nil 错误。

这是我的代码:

let request = NSMutableURLRequest(URL: NSURL(string: "linkHere")!)
request.HTTPMethod = "POST"
let postString = "sol=\(name)&sector=\(sector)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

if error != nil {
print("error=\(error)")
return
}

print("response = \(response)")

let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
do {
self.json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
} catch let error as NSError{
print("TEST Error \(error)")
}

if let parseJSON = self.json {


dispatch_async(dispatch_get_main_queue())
{

let storyboard = UIStoryboard(name: "Main", bundle: nil)

let vc = storyboard.instantiateViewControllerWithIdentifier("detailView") as! detailViewController
let x = parseJSON["sector"] as! String
vc.secLab = x
self.presentViewController(vc, animated: true, completion: nil)

}
}

}
task.resume()

在我的控制台日志中,我可以看到数据,请参见下图:

enter image description here

我做错了什么?

最佳答案

基本上,在捕获错误并仅打印错误后继续执行“良好”代码是一个坏主意。

如果您在 try 分支中展开转换类型,它会在成功时成为非可选类型,否则会捕获相应的错误。

语法应该是这样的

do {
self.json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as! [AnyObject]
dispatch_async(dispatch_get_main_queue())
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)

let vc = storyboard.instantiateViewControllerWithIdentifier("detailView") as! detailViewController
let dict = self.json[0] as! [String:AnyObject]
let x = dict["sector"] as! String
vc.secLab = x
self.presentViewController(vc, animated: true, completion: nil)
}
} catch let error as NSError{
print("TEST Error \(error)")
}

关于swift - NSURLSession:在展开可选值时意外发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34269459/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com