简体   繁体   English

iOS SWIFT 2-将Http json数组发送到服务器

[英]IOS SWIFT 2 - Http Post json array to server

I want to send data from my iOS app to a PHP sever in JSON format. 我想将数据从我的iOS应用发送到JSON格式的PHP服务器。 I am doing this at the backend with the following code: 我正在使用以下代码在后端执行此操作:

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

 $email         = $data['email'];
 $user_password = $data['password'];

I want to send data in a JSON variable such that I can accept the data in the JSON variable and then extract the fields one by one. 我想在JSON变量中发送数据,这样我就可以接受JSON变量中的数据,然后一个一个地提取字段。

At the moment, I am doing this in my iOS app with the following Swift code: 目前,我正在使用以下Swift代码在iOS应用中执行此操作:

func login(){
        let email:NSString = txtEmail.text!
        let password:NSString = txtPassword.text!
        let post:NSString = "username=\(email)&password=\(password)"

        NSLog("PostData: %@",post);

        let url:NSURL = NSURL(string:"http://example.com/test.php")!

        let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

        let postLength:NSString = String( postData.length )

        let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.HTTPBody = postData
        request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        var reponseError: NSError?
        var response: NSURLResponse?

        var urlData: NSData?
        do {
            urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
        } catch let error as NSError {
            reponseError = error
            urlData = nil
        }

        if ( urlData != nil ) {
            let res = response as! NSHTTPURLResponse!;

            NSLog("Response code: %ld", res.statusCode);

            if (res.statusCode >= 200 && res.statusCode < 300)
            {
                let responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

                NSLog("Response ==> %@", responseData);

                do {
                    let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary

                    let success:NSInteger = jsonData!.valueForKey("success") as! NSInteger

                    NSLog("Success: %ld", success);

                } catch let error as NSError {
                    print(error.localizedDescription)
                }
            }
        }    
}

I think I have to send a JSON array, but I don't know how can I save the variables in the array and send the JSON array to the PHP server. 我想我必须发送一个JSON数组,但是我不知道如何将变量保存在数组中并将JSON数组发送到PHP服务器。 Anyone have any ideas? 有人有想法么?

You can do this by creating an array of dictionaries: 您可以通过创建字典数组来做到这一点:

var user_outer_arrary = [[String:Any]]()
var user_inner_array = [String: Any]();
var jsonData : Data? = nil

let user_data :[String:Any]=["email": email,"password": password];

user_outer_arrary.append(user_data);
user_inner_array=["json": user_outer_arrary]

Then convert to JSON: 然后转换为JSON:

do
{
    jsonData = try JSONSerialization.data(withJSONObject: user_inner_array, options: JSONSerialization.WritingOptions.prettyPrinted)
}
catch
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM