David David - 1 year ago 100
iOS Question

Xcode, PHP; Having trouble with retrieving data from PHP/MySQL with SwiftyJSON-master

I'm developing an iOS app with Xcode and Swift.

I need to load some data from my MySQL database in my app. I think it's reasonable to do this with JSON (or is there something against it?).

To make it easier I want to use SwiftyJSON-master.

I found this working code on SO:

class ViewController: UIViewController {

var dict = NSDictionary()

@IBOutlet weak var authorLbl: UILabel!
@IBOutlet weak var quoteLbl: UILabel!

override func viewDidLoad() {


let urlString = "http://api.theysaidso.com/qod.json"

if let url = NSURL(string: urlString) {

if let data = try? NSData(contentsOfURL: url, options: []) {

let json = JSON(data: data)


let auther = json["contents"]["quotes"][0]["author"].stringValue

let quote = json["contents"]["quotes"][0]["quote"].stringValue

authorLbl.text = auther

quoteLbl.text = quote

But when trying it with my own PHP script it doesn't work.

I think it's because of the different outputs. The (working) PHP script from the SO post I found is like this:

{"success":{"total":1},"contents":{"quotes":[{"quote":"I put instant coffee in a microwave oven and almost went back in time.","length":"70","author":"Steven Wright","tags":["coffee","funny","humor","thetimes","time"],"category":"funny","id":"LvFg2QsKr_FoCH_lwryQ5geF"}]}}

Using my own PHP scrip output is like this:
[{"a":"John Eve","b":"Cupertino","c":"Green","d":"Apple"},{"a":"Sarah Jones","b":"Berlin","c":"Red","d":"Pear"}]

The syntax seem to bee completely different.

This is my PHP script/code:

$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include "$root/config.php";

$query = "SELECT * FROM users";
$stmt = $pdo->prepare($query);

$userData = array();

$userData[] = $row;
echo json_encode($userData);

What am I doing wrong? How can I influence the syntax? Or is it another problem?

P.S.: Is it reasonable to use this library or is something against it?

3li 3li
Answer Source


Your php file returns a correct json format. You can access to the data simply like this:

print(json[0]["a"]) // John Eve
print(json[0]["b"]) // Cupertino
// ...
print(json[1]["a"]) // Sarah Jones
print(json[1]["c"]) // Red