當我嘗試獲取數據時,出現以下錯誤。在互聯網上我讀到它,因爲PHP腳本是無效的,不返回JSON數據。但PHP腳本運行良好,並輸出正確的數據。嘗試從php腳本獲取Json數據時出錯
錯誤消息:
錯誤域= NSCocoaErrorDomain代碼= 3840「JSON文本不與陣列或對象和選項,允許片段未設置啓動」。的UserInfo = {NSDebugDescription = JSON文字不與數組或對象和期權開始允許未設定片段。}
我試圖讓碎片,但後來我得到的只是另一個錯誤信息。
這裏是SWIFT代碼,我試圖讓數據:
let myUrl = NSURL(string: "http://xxxxxxxxxxx.xxx/xxxxxxxx.php")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let postString = "userEmail=\(userEmail!)&userPassword=\(userPassword!)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
dispatch_async(dispatch_get_main_queue())
{
if(error != nil)
{
var alert = UIAlertController(title: "Achtung", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}
print("1")
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json {
let userId = parseJSON["userId"] as? String
if(userId != nil)
{
print("SUCESS FUCKER")
let mainView = self.storyboard?.instantiateViewControllerWithIdentifier("main") as! FlickrPhotosViewController
let mainPageNavi = UINavigationController(rootViewController: mainView)
//open mainView
let appdele = UIApplication.sharedApplication().delegate
appdele?.window??.rootViewController = mainPageNavi
} else {
let userMassage = parseJSON["message"] as? String
let myAlert = UIAlertController(title: "Alert", message: userMassage, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion: nil)
}
}
} catch{
print(error)
print("FAILED CATCHED")
}
}
}).resume()
,這是PHP文件的重要組成部分:
$userSecuredPassword = $userDetails["user_password"];
$userSalt = $userDetails["salt"];
if($userSecuredPassword === sha1($userPassword . $userSalt))
{
$returnValue["status"]="200";
$returnValue["userFirstName"] = $userDetails["first_name"];
$returnValue["userLastName"] = $userDetails["last_name"];
$returnValue["userEmail"] = $userDetails["email"];
$returnValue["userId"] = $userDetails["user_id"];
} else {
$returnValue["status"]="403";
$returnValue["message"]="User not found";
echo "failed";
echo json_encode($returnValue);
return;
}
echo json_encode($returnValue);
$的returnValue返回此當我打印出來: 陣列([狀態] => 200 USERFIRSTNAME] =>保羅[USERLASTNAME] => Heinemeyer [USEREMAIL] => paul_heine [用戶id] => 63)
幾個無關的觀察:1.你真的應該是百分比轉義你添加到發佈請求正文的值(例如,如果你的密碼有一個'&'或'+'字符,它不會被捕獲正確)。 2.你可能想在php中包含一個'header(「Content-Type:application/json」);'。這不是技術上的要求,但這是一個很好的做法。 3.您還應該將原始請求的「Content-Type」設置爲「application/x-www-form-urlencoded」。 4.考慮使用Alamofire讓你脫離正確創建請求和解析響應的雜草。 – Rob