我有返回json编码值的php文件,当我转到http地址时,它们会给我值,但是
我无法从服务器端获得应用程序的价值我已经尝试了很多次,但都没有得到

func loadData() {

    let url = NSURL(string: "http://example.com/getExpo.php")
    let request = NSMutableURLRequest(URL: url!)

    // modify the request as necessary, if necessary

    NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

        if error != nil {
            // Display an alert message

            print(error)

            return
        }

        do {

            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary


                if (json != nil) {

                    //let userId = parseJSON["userId"] as? String

                    // Display an alert message
                    let userMessage = json!["id"] as? String

                    print(userMessage)

                } else {

                    // Display an alert message
                    let userMessage = "Could not fetch Value"
                    print(userMessage)

                }



        } catch  {

            print(error)

        }

    }).resume()


}

任何人都可以帮忙,谢谢!!

最佳答案

JSON响应是一个字典数组:
[{“id”:“115”,“expoName”:“aziz”,“expoDetails”:“aziz”,“expoPhone”:“aziz”,“expoLocation”:“aziz”}]
但你想把它当作字典:

let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary

当然,解决方法是将其作为数组进行投射:
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray

如果可以,最好使用Swift类型:
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String:AnyObject]]

例如,可以使用循环:
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String:AnyObject]] {
    for item in json {
        let userMessage = item["id"] as? String
    }
}

08-03 16:58