在swift中使用JSON收到的Int

时间:2016-04-06 17:20:53

标签: ios json swift

我的php发送一个JSON对象,其中包含一个只有一个名为check的字段的关联数组。该字段包含10。我想使用此整数来创建值为0的警报。我试图创建一个名为log的外部方法var,我尝试给出名称的值,但它不起作用。

@IBAction func LogIn(sender: UIButton) {

    let verify = 0

    let bodyString = "a=\(User_log.text!)&b=\(Password_log.text!)"
    let bodyData = bodyString.dataUsingEncoding(NSUTF8StringEncoding)

    let request = NSMutableURLRequest(URL: NSURL(string: "http://mysite/myFolder/login.php")!)
    request.HTTPBody = bodyData
    request.HTTPMethod = "POST"

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if data == nil {
            print("request failed \(error)")
        }

        do{
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: Int]
            if let name = json!["check"] {
                if name == verify{
                    log = 0
                }
                else{
                    log = 1
                }
            }
        }catch {
            print("bom bom bom error")
        }
    }
    task.resume()

}

1 个答案:

答案 0 :(得分:0)

NSJSONSerialization.JSONObjectWithData为您[String: AnyObject]提供[String: Int]。此外,“检查”的值为NSNumber而不是Int

请尝试以下方法:

let data = try NSJSONSerialization.dataWithJSONObject(["check": "1", "other": "test"], options: NSJSONWritingOptions.init(rawValue: 0))

var log = 0

if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject] {
    log = json["check"]?.integerValue ?? 0
}