我尝试为服务器创建包含Background和Main队列的请求方法。最后,此方法应从服务器返回NSDictionary
我的响应。
func sendRequest(UrlString urlString:String,MethodString method:String)->(NSDictionary) {
DispatchQueue.global(qos: .background).async {
var request = URLRequest(url: URL(string:urlString)!)
request.httpMethod = method
//let postString = "id=13&name=Jack"
//request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
DispatchQueue.main.async {
do {
let jsonDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject] as NSDictionary
return jsonDictionary
} catch {
//Handle the error
}
//return airports
}
}
task.resume()
}
现在当尝试在主队列中返回jsonDictionary
时,它会向我显示此错误:
void函数中出现意外的非void返回值
现在我不知道如何解决这个问题
我使用的是Xcode 8
,iOS8
和Swift 3
请帮帮我
谢谢。
答案 0 :(得分:4)
您已实施至少两个异步操作,但它们无法返回值。对于异步操作,您应该使用如下的完成处理程序:
func sendRequest(urlString: String, method: String, completion: @escaping (_ dictionary: NSDictionary?, _ error: Error?) -> Void) {
DispatchQueue.global(qos: .background).async {
var request = URLRequest(url: URL(string:urlString)!)
request.httpMethod = method
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
completion(nil, error)
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
// make error here and then
completion(nil, error)
return
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
DispatchQueue.main.async {
do {
let jsonDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] as NSDictionary
completion(jsonDictionary, nil)
} catch {
completion(nil, error)
}
}
}
task.resume()
}
}