php - 如何从 post 请求 swift 3 中解析 JSON

标签 php ios json swift xcode

我这里有以下代码,它是与 phpMyAdmin 对话后请求的结果。服务器正在回显以下 JSON 文件。

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

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

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

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

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终端中输出的结果。

        `{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);

?>

最佳答案

尝试用这个替换你的错误行。在您的代码中,您应该通过 if let 移除强制解包和检查值。我的回答只是帮助您快速解决错误。

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

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

关于php - 如何从 post 请求 swift 3 中解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44804593/

相关文章:

PHP登录重定向流程

php - HTML/PHP if-else 语句

ios - Parse.com 查询字符串是否包含在数组中

ios - 在 iPhone 应用程序中安全地存储远程数据库凭据

javascript - 以预定义格式的表格格式显示 JSON 数据

PHP 命名空间和全局自动加载单个文件

php - 避免返回到页面顶部

iphone - Xcode:归档时配置配置文件过期消息,但所有配置文件都是最新的

python - 将 open() 作为 json.load() 参数传递会使文件句柄保持打开状态吗?

javascript - D3.js - 在图表中添加和自定义文本