2

I have the following code here that is a result of a post request talking to phpMyAdmin. The following JSON file is being echoed by the server.

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

Now I can get the JSON correctly onto my phone, but I am having trouble parsing it.

I have been following the guide listed here Xcode Json Example

Here is my code so far:

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()
}`

Here is the result of the output in the xcode terminal after I just print the JSON data.

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

Backend PHP code:

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

?>
2
  • If your backend expects JSON, why would you encode your data in .utf8? Encode it as JSON. And when decoding JSON, don't use NSDictionary and NSArray, but use native Swift structs. Commented Jun 28, 2017 at 14:10
  • My backend does not expect JSON, it's a php file that handles post requests for account information regarding test scores. I have just been following the guide listed above. Commented Jun 28, 2017 at 14:13

1 Answer 1

1

Try to replace your error lines with this. In your code, you should remove the force unwrap and check values by if let. My answer is just a quick help to solve your error.

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

print(login + " --- " + memoryScore)
Sign up to request clarification or add additional context in comments.

1 Comment

@NikP My pleasure. Happy coding :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.