0
我嘗試使請求到服務器的方法包含Background和Main隊列。最後,這個方法應該從服務器返回我的響應的NSDictionary
。在請求到服務器iOS的void函數中發生意外的非void返回值Swift 3
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
,它表明我這個錯誤:
Unexpected non-void return value in void function
現在我不知道如何解決這個問題。我正在使用Xcode 8
,iOS8
和Swift 3
。
請幫幫我。
謝謝。
有了這個工作函數,你如何調用它?我理解urlString和方法,以便完成我不知道,謝謝你的例子和解釋。 – LiTHiUM2525
它可以這樣調用: 'sendRequest(urlString:「http:// localhost」,方法:「GET」){字典,錯誤 }' –
我需要另一個細節,我叫它:sendRequest(urlString :「https://localhost/signup.php」,方法:「POST」){dictionary,error in}。數據正確傳輸到我的PHP。回覆iOS時,我收到: responseString:「{\\\」exception \\\「:false,\\\」success \\\「:false,\\\」status \\\「: - 9 ,\\\「message \\\」:\\\「This username already exists!\\\」}}「」) CATCH ERROR!爲什麼回答不會去jsonDictionary – LiTHiUM2525