2017-06-28 19 views
2

ここにphpMyAdminとのポストリクエストの結果である次のコードがあります。次のJSONファイルがサーバーによってエコーされています。投稿リクエストswiftからJSONを解析する方法3

{"account:[{"login":"Nik","id":"0","consent":"0","surveyScore":"0","memoryScore":"0","towerScore":"0","tappingScore":"0"}]} 

私の電話にJSONを正しく取得できますが、解析に問題があります。

私はここでXcode Json Example

ここに記載されているガイドを追ってきたことはこれまでに私のコードです:私はJSONデータを印刷した後

ここ
public func sqlAccount(login: String, pass: String, model:userModel) { 

// POST REQUEST Only, see php file for web service. 
let loci = "http://IPAddressConcealed/" 
let appended = loci + "account.php" 

var request = URLRequest(url: URL(string: appended)!) 
request.httpMethod = "POST" 
let postString = "login=\(login)&pass=\(pass)" 
request.httpBody = postString.data(using: .utf8)! 

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
    if let reponse = response { 
     print(reponse) 
    } 
    if let data = data { 
     //print(data) 

     do{ 
      var accountJson: NSDictionary! 
      let json = try JSONSerialization.jsonObject(with: data, options: []) 
      accountJson = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary 
      print(json) 

      //getting the json array account from the response 

      let account: NSArray = accountJson["account"] as! NSArray; 

      // these two lines I am getting errors on 
      let login: String = account[0]["login"] as! String 
      let memoryScore: Int = account[0]["memoryScore"] as! Int 

     } catch { 
      print(error) 
     } 
    } 
} 
task.resume() 
}` 

は、Xcodeの端子で出力した結果です。

 `{account =  (
      { 
     consent = 0; 
     id = 0; 
     login = Nik; 
     memoryScore = 0; 
     surveyScore = 0; 
     tappingScore = 0; 
     towerScore = 0; 
    } 
    ); }` 

バックエンドのPHPコード:

<?php 

// Create connection 
$con=mysqli_connect("localhost","root","root","sunnytest"); 

// Check connection 
if (mysqli_connect_errno()) 
{ 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

// This SQL statement selects ALL from the table 'Locations' 
//$sql = "SELECT * FROM accounts"; 



// Check if there are results 
if ($result = mysqli_query($con, $sql)) 
{ 
           // If so, then create a results array and a temporary one 
            // to hold the data 
            $response = array(); 

            $response['account'] = array(); 
            $tempArray = array(); 

            // Loop through each row in the result set 
            while($row = $result->fetch_object()) 
            { 
             // Add each row into our results array 
            $tempArray = $row; 
             array_push($response['account'], $tempArray); 
            } 

            // Finally, encode the array to JSON and output the results 
            printf(json_encode($response)); 
} 

// Close connections 
mysqli_close($con); 

?> 
+0

バックエンドでJSONが必要な場合、なぜデータを.utf8でエンコードするのですか? JSONとしてエンコードします。また、JSONをデコードするときは、NSDictionaryとNSArrayを使用せず、ネイティブSwift構造体を使用してください。 –

+0

私のバックエンドはJSONを期待していません。テストポイントに関するアカウント情報の投稿要求を処理するphpファイルです。私はちょうど上記のガイドに従っています。 –

答えて

1

は、これであなたのエラー行を交換してください。あなたのコードでは、アンラップ力とチェック値を外してif letで削除する必要があります。私の答えはあなたのエラーを解決するための簡単なヘルプです。

let firstDic = account[0] as! NSDictionary 
let login = firstDic["login"] as! String 
let memoryScore = firstDic["memoryScore"] as! String 

print(login + " --- " + memoryScore) 
+0

これはうまくいきました。ファンニングありがとうございました –

+0

@NikP私の喜びです。ハッピーコーディング:) –

関連する問題