1
我試着爲我的POST請求創建一個輔助類,並且想要返回響應。但是,由於發佈請求是異步的,這讓我感到有點困惑。使用輔助函數發送POST請求
我試過返回NSString,但它不讓我返回response
和responseString
。它只是讓我把return "A"
。我試圖使用-> NSURLResponse
,但無法使其工作。
製作這種幫手方法的正確方法是什麼? (這也是好的,如果我做一個檢查後,我得到響應,並返回true或按虛假的響應)
class func hello(name: String) -> NSString {
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!)
request.HTTPMethod = "POST"
let postString = "Hi, \(name)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
return "A"
}
哇!王牌男人!謝謝!!! – senty
注意行更改'let responseString = String(data:data !,編碼:NSUTF8StringEncoding)'將NSString更改爲String以更靈活 – Fonix
還注意到我還沒有包含任何錯誤處理代碼,您自己如何處理 – Fonix