iOS Swift JSON检索数据问题

时间:2015-02-23 08:43:32

标签: ios swift alamofire swifty-json

我想做什么:检索我的静态单元格标签我的JSON查询的返回值。

我的问题是什么:我不能这样做。无法返回单个值来更改我的标签。

我尝试了什么:首先,我安装了Alamofire和SwiftyJSON库。其次,我做了我的PHP脚本,导致正确的JSON数据。我在故事板中创建了标签,并在我的UITableViewController中创建了@IBOutlet UILabel。第三,我做了我的Alamofire请求,我可以获得整个数据的输出。

我不能做的事情:我无法获得个人字段来​​替换我的标签。我想从我的JSON中检索[用户名] [性别] [位置] [生日] [手机] [签名],并用此退货替换我的标签。但是当我想检索[手机]时,我的结果是零。

我还认为我的JSON有问题,因为它似乎没有返回Array而只返回Dictionary

我的tableviewcontroller

          import UIKit
import Alamofire
import SwiftyJson

class PersonalDetails: UITableViewController {

    required init(coder aDecoder: NSCoder) {
        println("init PersonalDetails")
        super.init(coder: aDecoder)
    }

    deinit {
        println("deinit PersonalDetails")
    }

    var usersData = [PersonalDetailsData]()

    @IBOutlet weak var dataUsername: UILabel!
    @IBOutlet weak var dataGender: UILabel!
    @IBOutlet weak var dataArea: UILabel!
    @IBOutlet weak var dataBirthday: UILabel!
    @IBOutlet weak var dataMobilePhone: UILabel!
    @IBOutlet weak var dataSignature: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
        var username = prefs.valueForKey("USERNAME") as NSString
//load and parse the JSON into an array
        Alamofire.request(.GET, "http://mywebsite/app/data/jsonpersodata.php", parameters: ["username": username]).responseJSON { (request, response, data, error) in

            let swiftyJSONObject = JSON(data!)
            if (error != nil)
            {
                // got an error in getting the data, need to handle it
                println("error calling GET usersdata")
                println(error)
            }
            else if let data: AnyObject = data
            {
                // handle the results as JSON, without a bunch of nested if
                let userdata = JSON(data)
                if let mobilephone: String = userdata [0]["mobilephone"].stringValue {
                self.dataMobilePhone.text = mobilephone
                }

                               }

        }

    }



    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
           }

    @IBAction func logoutTapped(sender : UIButton) {

        let appDomain = NSBundle.mainBundle().bundleIdentifier
        NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain!)

        self.performSegueWithIdentifier("logout", sender: self)
    }


    }

我的班级

import Foundation

class PersonalDetailsData: NSObject {

    var dataUsername:String?
    var dataGender:String?
    var dataArea:String?
    var dataBirthday:String?
    var dataMobilePhone:String?
    var dataSignature:String?
}

我的json

[
  {
    "username": "username1",
    "gender": "?",
    "location": "??",
    "birthday": "1983/01\/16",
    "mobilephone": "136777777",
    "signature": null
  }
]

我的php

<?php
header('Content-type: application/json');
/* include db.config.php */
include_once("config.php");
// Get user id
$id = isset($_GET['username']) ? mysql_real_escape_string($_GET['username']) : “”;

if(empty($id)){
    $data = array ("result" => 0, "message" => 'Wrong user id');
} else {
// get user data
$sql = mysql_query("SELECT username, gender, location, birthday, mobilephone, signature FROM users WHERE username='$id'");

$data = array ();

 while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
        $row_array['username'] = $row['username'];
        $row_array['gender'] = $row['gender'];
        $row_array['location'] = $row['location'];
        $row_array['birthday'] = $row['birthday'];
        $row_array['mobilephone'] = $row['mobilephone'];
        $row_array['signature'] = $row['signature'];
        //push the values in the array
        array_push($data,$row_array);
 }
 echo json_encode($data);

mysql_close($conn);
/* JSON Response */
}
?>

1 个答案:

答案 0 :(得分:1)

您返回的JSON实际上是一个数组,而不是您期望的对象的直接值(请参阅原始JSON中的[]?它们代表一个数组)。

以下是解析JSON数组中第一项的方法:

            // handle the results as JSON, without a bunch of nested if
            let userdata = JSON(data)
            if let mobilephone: String = userdata[0]["mobilephone"].string {
                self.dataMobilePhone.text = mobile phone
            }
            // etc.