IOS SWIFT 2 - Http Post json数组到服务器

时间:2016-01-02 19:25:00

标签: php ios json swift

我想将我的iOS应用程序中的数据以JSON格式发送到PHP服务器。我在后端使用以下代码执行此操作:

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

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

我想在JSON变量中发送数据,以便我可以接受数据 JSON变量然后逐个提取字段。

目前,我正在使用以下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)
                }
            }
        }    
}

我想我必须发送一个JSON数组,但我不知道如何在数组中保存变量并将JSON数组发送到PHP服务器。有人有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以通过创建字典数组来完成此操作:

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]

然后转换为JSON:

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