【问题标题】:POST json object in a form variable on a sever在服务器上的表单变量中发布 json 对象
【发布时间】:2016-01-03 12:42:54
【问题描述】:

你好,我正在开发 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' 的表单变量中。

【问题讨论】:

    标签: php ios arrays json swift


    【解决方案1】:

    我强烈建议使用库,例如​​ 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)")
                 }
             }
    

    【讨论】:

      猜你喜欢
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多