如何从post request swift 3中解析JSON

时间:2017-06-28 13:56:58

标签: php ios json swift xcode

我在这里有以下代码,这是与phpMyAdmin交谈的帖子请求的结果。服务器正在回显以下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()
}`

现在我可以将JSON正确地放到我的手机上,但是我在解析它时遇到了问题。

我一直在遵循此处列出的指南Xcode Json Example

到目前为止,这是我的代码:

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

这是我打印JSON数据后xcode终端输出的结果。

<?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);

?>

后端PHP代码:

unsigned int

1 个答案:

答案 0 :(得分:1)

尝试用此替换您的错误行。在您的代码中,您应该删除强制解包并按if let检查值。我的答案只是帮助您解决错误。

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

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