Swift Xcode 6.1.1 POST请求未发布

时间:2014-12-27 17:05:43

标签: php ios xcode post swift

我只想将Swift中的一些数据发布到PHP脚本中。我已经用Google搜索了大约两天,每个人似乎都在做同样的事情,但它并不适合我。我在viewDidLoad()

上触发了这个Swift代码
override func viewDidLoad() {
    super.viewDidLoad()

    let request = NSMutableURLRequest(URL: NSURL(string: "http://mywebsite.com/scriptToHandlePOST.php")!) // it forces me to add the !
    request.HTTPMethod = "POST"

    var err: NSError?
    let postString = "var1=value1&var2=value2".dataUsingEncoding(NSUTF8StringEncoding)
    var postLength:NSString = String( postString!.length )

    request.HTTPBody = postString
    request.setValue(postLength, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error -> Void in
        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)

        println(response) // this returns a 200
        println(strData!) // this returns an empty array of the $_POST variable
    }

    task.resume() // this is needed to start the task

}

我的PHP脚本只是试图获取$ _POST数据:

<?php

print_r($_POST);

?>

由于$ _POST返回一个空数组,我怀疑POST请求永远不会进入我的网站。你看到代码中有什么问题吗?

0 个答案:

没有答案