[英]Not receiving correct data at PHP server when sending an HTTP POST Request from iOS 9 / Swift 2.0
[英]swift POST request not sending data to server
從我的iPhone應用程序的登錄視圖中,我可以獲得要發送到服務器的用戶名和密碼。 我編寫了簡單的腳本,只是為了檢查我向服務器發送POST請求的功能是否正常。 我沒有任何錯誤,但是我的腳本似乎得到了空的POST變量。 這是我向PHP服務器腳本發送參數的函數:
func postDataToURL() {
let json = [ "username" : "vanja", "password" : "dinamo", "iphone" : "1" ]
print (json)
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
// create post request
let url = NSURL(string: "http://www.pnc.hr/rfid/login.php")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
// insert json data to the request
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error 55 -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
print("Result 34 -> \(result)")
} catch {
print("Error 43-> \(error)")
}
}
task.resume()
}
catch {
//handle error. Probably return or mark function as throws
print(error)
return
}
}
這是我的PHP腳本:
<?php
if (isset($_POST['username']))
$username = $_POST['username'];
else $username = "nista";
if (isset($_POST['password']))
$password = $_POST['password'];
else $password = "nista";
if (isset($_POST['iphone']))
$iphone = $_POST['iphone'];
else $iphone = "nista";
$arr = array('username' => $username, 'password' => $password, 'loggedIn' => 1, 'token' => 'ldsakj832WE32', 'iphone' => $iphone );
echo json_encode($arr);
?>
問題在於該腳本沒有獲取我的任何POST變量。
問題是:從Swift我已經發送了json文件,而不是POST變量。 所以我沒有用$ _POST從php中獲取變量。 我需要獲取json文件並進行如下編碼:
$json = file_get_contents('php://input');
//echo $json shoulkd show the json string
$array = json_decode($json, true);
// var_dump($arr) should show the array structure
$username = $array['username'];
$password = $array['password'];
$iphone = $array['iphone'];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.