无法在HOME.VC文本标签中显示JSON结果

时间:2015-08-06 21:28:43

标签: ios json swift

我试图在我的视图控制器上显示Json结果(温度和湿度)(分别是temperatureDisp和humidityDisp),但它似乎不起作用。

class HomeVC: UIViewController {

    @IBOutlet var usernameLabel: UILabel!

    @IBOutlet var temperatureDisp: UILabel!

    @IBOutlet var humidityDisp: UILabel!

    @IBAction func logoutTapped(sender: AnyObject) {
        let appDomain = NSBundle.mainBundle().bundleIdentifier
        NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain!)

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


    override func viewDidAppear(animated: Bool) {
        let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
        let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
        if (isLoggedIn != 1) {
            self.performSegueWithIdentifier("goto_login", sender: self)
        } else {
            self.usernameLabel.text = prefs.valueForKey("USERNAME") as! NSString as String
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var url2 : String = "http://admin:xxxxxxx@xxxxxx/xxxxx.fr/metrics2.php"
        var request2 : NSMutableURLRequest = NSMutableURLRequest()
        request2.URL = NSURL(string: url2)
        request2.HTTPMethod = "GET"
        NSURLConnection.sendAsynchronousRequest(request2, queue: NSOperationQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
            var  error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
            let jsonResult : NSArray! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: error) as! NSArray
            if (jsonResult != nil) {
                println(jsonResult)

            } else {
                println("There is a problem")
            }

            var temperature = jsonResult[0].valueForKey("temperature") as! String
            var humidity = jsonResult[0].valueForKey("humidite") as! String

            println(temperature)
            println(humidity)


            self.humidityDisp.text = temperature

        })


    }


}}

这就是变量jsonResult的外观:

(
        {
        Id = 117;
        date = "2015-04-06";
        humidite = "45.3";
        login = raspberrypi;
        luminosite = "\U00e9teinte";
        temperature = "18.4";
        time = "16:25:21";
    }
)

1 个答案:

答案 0 :(得分:0)

我不确定你的意思&#34;它似乎不起作用&#34;,但是从你的代码中我至少可以假设你没有从你的JSON结果中得到你期望的值,但更有可能你的应用程序像疯了一样崩溃。如果你想在Swift中编写应用程序,你绝对必须了解选项并学习如何正确使用它们。阅读The Swift Programming Language - 并彻底。正如您的代码现在一样,通过使用as!强制解包并使用隐式展开的类型(后面跟!),您忽略了选项的整个概念并让自己陷入崩溃。

因此,假设没有网络或解析错误,并假设您正在解析的JSON字符串有一个数组作为其根对象,则以下内容应该有效。我已经冒昧地打字和打开你的变量,以及清理一些残余物。

class HomeVC: UIViewController {

    @IBOutlet var usernameLabel: UILabel!
    @IBOutlet var temperatureDisp: UILabel!
    @IBOutlet var humidityDisp: UILabel!

    @IBAction func logoutTapped(sender: AnyObject) {
        if let appDomain = NSBundle.mainBundle().bundleIdentifier {
            NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain)
        }
        self.performSegueWithIdentifier("goto_login", sender: self)
    }

    override func viewDidAppear(animated: Bool) {
        let prefs = NSUserDefaults.standardUserDefaults()
        let isLoggedIn = prefs.boolForKey("ISLOGGEDIN")
        if isLoggedIn {
            self.performSegueWithIdentifier("goto_login", sender: self)
        } else {
            if let username = prefs.stringForKey("USERNAME") {
                self.usernameLabel.text = username
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var url2 = "http://admin:xxxxxxx@xxxxxx/xxxxx.fr/metrics2.php"
        var request2 = NSMutableURLRequest()
        request2.URL = NSURL(string: url2)
        request2.HTTPMethod = "GET"
        NSURLConnection.sendAsynchronousRequest(request2, queue: NSOperationQueue()) { (response: NSURLResponse!,data: NSData!,error: NSError!) in
            var parseError:NSError?

            if let data = data, let jsonResults = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as? NSArray {

                println( jsonResults )

                if let result = jsonResults.firstObject as? [String : AnyObject] {
                    if let humidity = result["humidite"] as? String {
                        self.humidityDisp.text = humidity
                    }
                    if let temperature = result["temperature"] as? String {
                        self.temperatureDisp.text = temperature
                    }
                }
            } else {
                println("There is a problem: \(parseError)" )
            }
        }
    }
}