2016-08-21 112 views
0

當我嘗試獲取數據時,出現以下錯誤。在互聯網上我讀到它,因爲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

幾個無關的觀察:1.你真的應該是百分比轉義你添加到發佈請求正文的值(例如,如果你的密碼有一個'&'或'+'字符,它不會被捕獲正確)。 2.你可能想在php中包含一個'header(「Content-Type:application/json」);'。這不是技術上的要求,但這是一個很好的做法。 3.您還應該將原始請求的「Content-Type」設置爲「application/x-www-form-urlencoded」。 4.考慮使用Alamofire讓你脫離正確創建請求和解析響應的雜草。 – Rob

回答

2

當你正確地格式化PHP代碼,你會看到,在其他部分你有

echo "failed"; 
echo json_encode($returnValue); 

導致

failed{...} 

隨着錯誤消息已經指出,這種「JSON文字不與數組或對象開始。 ..「

也許有類似的輸出,如果其他部分。

+0

Sry,但我不明白你的解決方案,因爲這兩行代碼我進入了一個失敗的塊? @Olaf Dietsche –

+0

這不是一個解決方案,只是一個觀察,在其他情況下,PHP輸出確實以「失敗」開始,它既不是數組的開始[',也不是對象的開始'{' 。所以對於其他情況,刪除'echo「失敗」'。 –

+0

要充分調查這一點,您必須在客戶端輸出響應。在那裏你會看到,問題是什麼以及錯誤輸出來自哪裏。從你的問題中的部分代碼,我可以推斷出只有部分答案。 –

相關問題