从iOS 9/Swift 2.0发送HTTP POST请求时,在PHP服务器上未接收到正确的数据


Not receiving correct data at PHP server when sending an HTTP POST Request from iOS 9 / Swift 2.0

当我使用Swift将"username=abc&password=xyz"从iOS发布到index.php时,我必须在我的服务器上接收

$_POST["username"]//"abc"

$_POST["password"]//"xyz"

但我正在接收

$_POST["username"]//可选("abc")

$_POST["password"]//可选("xyz")

在找出错误时遇到麻烦。请提出合适的解决方案

注意:I am using Xcode 7.0.1, Swift 2.0, Simulator: iPhone 5, Deployment Target: iOS 9.0, Server = "Apache/2.4.12 (Win32) OpenSSL/1.0.1m PHP/5.6.11";

这是我的swift代码

let request = NSMutableURLRequest(URL:NSURL(string:"http://192.168.1.7/testSwiftPOST/index.php")!)
request.HTTPMethod = "POST"
let postString = "username=abc&password=xyz"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ (data, response, error) -> Void in
        if let Data = data {
            print(NSString(data: Data, encoding: NSUTF8StringEncoding)!) // this prints the data of the $_POST variable in the debug area
        }
}
task.resume()

这是我的php代码

<?php
    print_r($_POST);

以下是我在Xcode的调试区域中的输出:

Array
(
    [username] => Optional("abc")
    [password] => Optional("xyz")
)

仅供参考,我还在我的info.plist文件中添加了以下设置:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>192.168.1.7/</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

上面的代码在iOS 8.4的Xcode 6中运行得很好,但问题是在升级到iOS 9.0的Xcode 7后开始的。

dataUsingEncoding返回一个可选项。在发送请求之前,您必须先打开包装

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)!