【问题标题】:HTTP Post Request check in swift快速检查 HTTP Post 请求
【发布时间】:2015-07-29 11:45:52
【问题描述】:

我有 php 文件来检查从 swift ios 传递的值,我打印 json 数据,这是代码:

<?php
$said = $_REQUEST['sa_id'];
if($said == '123456') {
    $returnValue = array("said" => "true");
}else{
    $returnValue = array("said" => "false");
}
echo json_encode($returnValue);
?>

我还写了一个快速函数来检查返回的值,我的代码在第二次点击时工作成功,我想要它从第一次点击:

class ViewController: UIViewController {

    var saidResult = false;

    @IBOutlet var saidField: UITextField!
    @IBOutlet var labelField: UILabel!

    override func viewDidLoad(){
        super.viewDidLoad()
    }   

    @IBAction func checkSAID(sender: UIButton) {

        if ( isValidSAID(saidField.text) == false ) {
            labelField.text = "SAID is Invalid"
        } else {
            labelField.text = "Done"
        }
    }

    func isValidSAID(said2Test: String) -> Bool {

        let myUrl = NSURL(string: "http://*****.com/said.php");
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";

        // Compose a query string
        let postString = "sa_id=\(said2Test)";

        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            (data, response, error) in
            if error != nil {
                println("error=\(error)")
                return
            }

            // You can print out response object
            println("response = \(response)")

            // Print out response body
            let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("responseString = \(responseString)")

            //Let's convert response sent from a server side script to a NSDictionary object:
            var err: NSError?
            var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary

            if let parseJSON =myJSON {
                // Now we can access value of First Name by its key
                var saidValue = parseJSON["said"] as? String
                println("saidValue: \(saidValue)")

                if ((saidValue) == "true" ) {
                    self.saidResult = true;
                }

                println("saidResult: \(self.saidResult)");
            }
        }
        task.resume()
        println("saidResult: \(self.saidResult)");
        if ( self.saidResult == true ){
            return true
        } else {
            return false
        }

    }

}

正如我所说,在第一次单击时,saidResult 的值是 false,但之后它会采用 true 值

我该如何解决这个问题,或者有其他方法可以改进我的代码吗?

【问题讨论】:

    标签: php ios json swift


    【解决方案1】:

    我认为这可能是因为 http 请求在第一次点击时没有得到响应,而是在第二次点击时得到响应。

    你可以尝试用这个替换你的 checkSAID 函数。

    @IBAction func checkSAID(sender: UIButton) {
    
        let saidQueue = dispatch_queue_create("saidQueue", DISPATCH_QUEUE_CONCURRENT)
    
        // Do the checking on a background thread.
        dispatch_async(saidQueue, {
            if ( isValidSAID(saidField.text) == false ) {
        // As the UI updates are performed on the main queue, update the label on the main queue.
                dispatch_async(dispatch_get_main_queue()) {
                    labelField.text = "SAID is Invalid"
                })
            } else {
                dispatch_async(dispatch_get_main_queue()) {
                    labelField.text = "Done"
                })
            }
        })
    
    }
    

    【讨论】:

      【解决方案2】:

      最后,经过 4 天的测试,我解决了我的问题。

      我更改了isValidSAID功能代码:

      func isValidSAID(said2Test: String) -> Bool {
      
          var status: String = "";
      
          let myUrl = NSURL(string: "http://*****.com/said.php?sa_id=\(said2Test)");
          let data = NSData(contentsOfURL: myUrl!)
          let json = NSHSONSerialization.JSONObjectWithData(data!, option: nil, error: nil) as! NSDictionary
      
          status = (json["said"] as? String)!
          println(status)
      
          return ( status == "true" ) ? true : false
      }
      

      并解决了我的问题。

      【讨论】:

        猜你喜欢
        • 2016-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-01
        • 2011-03-16
        • 2011-10-29
        • 1970-01-01
        相关资源
        最近更新 更多