gpt4 book ai didi

ios - 预期返回 'NSURLSessionDataTask' 的函数中缺少返回值

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

我正在学习有关访问 API 和解析结果的教程。我正在逐字逐句地学习教程,但由于“预期返回‘NSURLSessionDataTask’的函数中缺少返回值”,我无法运行该程序

所以我将返回语句更改为“return NSURLSessionDataTask”,但随后收到错误消息“无法将类型为‘NSURLSessionDataTask.Type’的返回表达式转换为返回类型‘NSURLSessionDataTask’

我如何确定返回类型?我什至需要返回吗?因为在教程中没有 return 语句(我也试过没有 return )。

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()



}

最佳答案

您真的打算编写自己的名为 dataTaskWithRequest 的方法,它看起来就像同名的 NSURLSession 方法吗?问题是你说你正在编写一个返回 NSURLSessionTask 对象的方法,但你没有返回任何东西。

我认为您的意思类似于以下内容,将您自己的方法重命名为其他内容,并指定它本身不返回任何内容,因为它不是:

func performRequest() {
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()
}

关于ios - 预期返回 'NSURLSessionDataTask' 的函数中缺少返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33770703/

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