服务器上表单变量中的POST json对象


POST json object in a form variable on a sever

你好,我正在开发IOS SWIFT 2。我需要在一个变量中发送json对象,这样我就可以像一样访问json对象

$json = $_POST['json'];
        $data = json_decode($json, TRUE);
        $email         = $data['email'];
        $user_password = $data['password'];

现在数据像这个一样发布在服务器上

{
  "email" : "email",
  "password" : "password"
}

这是我正在使用的代码

func post() {
         let url:String = "http://example.com/test.php"
        let request = NSMutableURLRequest(URL: NSURL(string: url)!)
         let params = ["email":"email", "password":"password"] as Dictionary<String, String>
        //let request = NSMutableURLRequest(URL:url)
        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"
        do {
            let data = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
            let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)!
            print("dataString is  '(dataString)")
            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)

        } catch {
            //handle error. Probably return or mark function as throws
            print(error)
            return
        }
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            // handle error
            guard error == nil else { return }
            print("Response: '(response)")
            let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Body: '(strData)")
            let json: NSDictionary?
            do {
                json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
            } catch let dataError {
                // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
                print(dataError)
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: ''(jsonStr)'")
                // return or throw?
                return
            }

            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                let success = parseJSON["success"] as? Int
                print("Succes: '(success)")
            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '(jsonStr)")
            }
        })
        task.resume()
    }

我想以一个名为"json"的形式变量传递上面的json。

我强烈建议使用库,如Alamofire来处理此问题。自己做是乏味的。

一旦添加到Swift项目中,您就可以非常非常优雅地发送JSON参数:

Github页面示例:

let parameters = [
    "foo": [1,2,3],
    "bar": [
        "baz": "qux"
    ]
]
Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON)

然后,您可以使用现有的PHP代码来处理JSON。

编辑:

处理JSON也非常优雅:

Alamofire.request(.POST, url, etc).responseJSON { response in
             print(response.request)  // original URL request
             print(response.response) // URL response
             print(response.data)     // server data
             print(response.result)   // result of response serialization
             if let JSON = response.result.value {
                 print("JSON: '(JSON)")
             }
         }