2
我試圖向Web服務器發送POST請求,但是我試圖發送的值是在名爲temperatureValue的變量中。 Web服務器查找POST變量「temperature」。這是我如何宣佈我的postData。我如何傳遞這個變量?如何使用變量在Swift中發送POST請求
let postData = NSMutableData(data: "temperature=temperatureValue".dataUsingEncoding(NSUTF8StringEncoding)!)
的POST代碼的其餘部分包含下面,但我的主要問題是如何格式化上面,讓我的變量temperatureValue要保存到POSTDATA。
//Assign the url post address, post the data to the php page
let request = NSMutableURLRequest(URL: NSURL(string: "http://pi.access.com/stateBlinds.php")!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)
request.HTTPMethod = "POST"
request.HTTPBody = postData
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? NSHTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
它是可選的。我是否用圓括號內的問號打開它? – Dan
不,您可能會在構建將被轉換爲「NSData」的字符串時進行條件綁定。如果沒有'temperatureValue',我們只需要決定你想要做什麼(我假設你只是發送空字符串到服務器,但這取決於你的web服務是如何寫的。)請參閱修訂後的答案。 – Rob
真棒謝謝你 – Dan