I try to make method for request to server contain Background and Main queue. Finally this method should return NSDictionary
of my response from the server.
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()
}
And now when try to return jsonDictionary
in the main queue, it shows me this error:
Unexpected non-void return value in void function
And now I don't know how to fix this problem.
I am using Xcode 8
, iOS8
and Swift 3
.
Please help me.
Thank you.
You have implemented at least two async operations and they are can't return values. For async operations you should use completion handlers like this:
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()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.