在swift 2.2中阅读JSON的回复

时间:2016-05-06 13:12:59

标签: ios json swift2.2

我编写此代码以通过JSON发送带有2个变量(手机号码和客户密钥)的请求,并且我希望接收带有两个变量(id和已验证)的响应,但是我在阅读响应中收到错误我没有'知道为什么!

我在注册按钮内的此部分代码如下:

            do {

            let post:NSString = "dst=\(completenumber)&customer_key=\(self.CUSTOMER_KEY)"



            NSLog("PostData: %@",post)

            let regURL:NSURL = NSURL(string: "myreg URL here")!


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

            let postLength:NSString = String( postData.length )

            let request:NSMutableURLRequest = NSMutableURLRequest(URL: regURL)
            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)
               // print(urlData)
            } 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 Data ==> %@", responseData );

                    //var error: NSError?

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


                    let success:NSString = jsonData.valueForKey("verified") as! NSString
                    let resultid:NSString = jsonData.valueForKey("id") as! NSString

                    //[jsonData[@"success"] integerValue];

                    NSLog("Verified: %@", success);
                    NSLog("ID: %@", resultid);

                    if(success == "new")

                    {
                    NSUserDefaults.standardUserDefaults().setObject(resultid, forKey: "VerifiedID")


                    NSUserDefaults.standardUserDefaults().synchronize()

                    self.dismissViewControllerAnimated(true, completion: nil )

                    self.performSegueWithIdentifier("enter_pin", sender: self)
                    }


                }

            } else {
                let alertView:UIAlertView = UIAlertView()
                alertView.title = "Registration Failed!"
                alertView.message = "Connection Failure"
                if let error = reponseError {
                    alertView.message = (error.localizedDescription)
                }
                alertView.delegate = self
                alertView.addButtonWithTitle("OK")
                alertView.show()
            }

            } catch {
                let alertView:UIAlertView = UIAlertView()
                alertView.title = "Registration Failed!"
                alertView.message = "Server Error!"
                alertView.delegate = self
                alertView.addButtonWithTitle("OK")
                alertView.show()
            }

错误:

Response code: 200
Response Data ==> Error

(更新)JSON文件:

<?php
  require("lib.php");
  require ("src/mobile_verify_lib.php");
  require_once 'plivo.php';
  require_once dirname(__DIR__) . '/core/logentries/logentries.php';
  date_default_timezone_set('GMT');
  header('Content-Type: application/json');


 if (!$_GET[customer_key])
   {
     echo "Error";
     exit;
   }
 $kkey = $_GET[customer_key];
 $check_customer = check_customer($kkey);
 $customer_id = $check_customer[id];

 $src = "19178180011";
 $dst = $_GET[dst];
 #$text = $_GET[text];


 $pin = getpin();

 $vid = generateRandomString(16);

 $checktel = checktel($dst,$customer_id);

 if($checktel[status])
   {

  #echo "You already have a pending verification request<br>";
   if($_GET[clear] == "yes")
    {
    destroyvid($checktel[vid]);
    $js[id] = $checktel[vid];
    $js[verified] = "cleared";
    echo json_encode($js);
    exit;
  }
   destroyvid($checktel[vid]);

 }


 //Check mobile number format and type (Only Mobile type is accepted)
 $test = check_mobile($dst);

 if(!$test[valid])
   {
     $js[id] = "NONE";
     $js[verified] = "INVALID";
     echo json_encode($js);
     #echo '{"id":"NONE","verified":"INVALID"}';
     exit;
     }

   // End


  $dateandtime = date("Y-m-d H:i:s");



 $servername = "mysql.tmed.pw";
 $username = "ahmad";
 $password = "ahVb$4TrHA11";
 $dbname = "acticonnectverify";

 // Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
 // Check connection
 if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
 }

 $sql = "INSERT INTO phone_verification (vid, mobile_number, pin,   customer_id,dateandtime) VALUES ('$vid', '$dst', '$pin', '$customer_id' , '$dateandtime')";

if ($conn->query($sql) === TRUE) {
   # echo "New record created successfully";
  } else {
    # echo "Error: " . $sql . "<br>" . $conn->error;
}

  $conn->close();


 $text = "To verfiy your mobile number, Please enter this PIN: $pin";
 $js[id] = $vid;
 $js[tel] = $dst;
 $js[text] = "true";
 $js[verified] = "new";


 echo json_encode($js);
 #echo '{"id":"' . $vid . '","tel":"' . $dst .'","text":true,"verified":"new"}';

 sendsms($dst,$src,$text,$customer_id);


 ?>

1 个答案:

答案 0 :(得分:0)

我通过注释这些行并以正常方式传递完整的URL而不使用帖子数据来解决这个问题

//let post:NSString = "dst=\(completenumber)&customer_key=\(self.CUSTOMER_KEY)"
//let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
//let postLength:NSString = String( postData.length )
//request.HTTPBody = postData
//request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")