【发布时间】:2015-11-18 02:16:59
【问题描述】:
我正在学习有关访问 api 和解析结果的教程。我正在逐字遵循教程,但由于“预期返回 'NSURLSessionDataTask' 的函数中缺少返回值”,我无法运行该程序
所以我将返回语句更改为“返回 NSURLSessionDataTask”,但随后出现错误提示“无法将类型为 'NSURLSessionDataTask.Type' 的返回表达式转换为返回类型'NSURLSessionDataTask'
我如何确定返回类型?我还需要退货吗?因为在本教程中没有返回语句(我也尝试过没有返回)。
func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void)
-> NSURLSessionDataTask {
let postEndpoint: String = "http://jsonplaceholder.typicode.com/posts/1"
let urlRequest = NSURLRequest(URL: NSURL(string: postEndpoint)!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlRequest, completionHandler: {
(data, response, error) in
guard let responseData = data else {
print("Error: did not recieve data")
return
}
guard error == nil else {
print("error calling GET on /posts/1")
print(error)
return
}
// parse the resutl as JSON, since that's what the API provieds
let post: NSDictionary
do {
post = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as! NSDictionary
} catch {
print("error trying to convert data to JSON")
return
}
// now we have the post, let's just print it to prove we can access it
print("The post is: " + post.description)
if let postTitle = post["title"] as? String {
print("The title is: " + postTitle)
}
})
// and send it
task.resume()
}
【问题讨论】:
-
与手头的问题无关,但如果您多次调用此方法,您可能不应该每次都实例化一个新的
NSURLSession。使用NSURLSession.sharedSession()或实例化您自己的,但只执行一次。 -
谢谢!这段代码在教程中的方式有点令人困惑。 @Rob