Alamofire POST 参数没有通过

Alamofire POST parameters doesn't come through

我想向我的网站发送 post 请求。但我的 POST 请求似乎没有通过。

我的 PHP 文件,我需要在其中发送我的 POST 请求。

// just to check incoming POSTS

<?php
foreach ($_POST as $key => $value) {
    ?>
        <span style="display:block"><b><?php echo $key; ?></b>  - <?php echo $value; ?></span>
    <?php
}

// actual code

if($_POST["some_key"]=="some_data"){
    echo json_encode(["some","respons"],["test"]);
    exit();
}else{

// other code

}
?>

.swift 包含用于发送 post 请求的代码的文件:

import Foundation
import Alamofire

class ConnectApi{
    
    var data = Data()
    
    let urlPath: String = "http://localhost:8000/sites/mcms/api.php"

    let headers: HTTPHeaders = [
        "Accept": "application/json"
    ]
    
    func getData(parameters: [String: [String]]){
        AF.request(URL.init(string: urlPath)!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
            
            debugPrint(response) // just to see the response in more detail

            // ...

        }
    }
}

我在哪里传递 POST 参数:

let connection = ConnectApi()
        
let parameters: [String: [String]] = [
    "some_key": ["some_data"]
]
        
connection.getData(parameters: parameters)

这是我从 debugPrint(response):

得到的输出
[Request]: POST http://localhost:8000/sites/mcms/api.php
[Request Body]: 
{"REQUEST_API":["TEST"],"IOS_MCMS_REQUEST":["IOS_VALIDATED_V0_1"]}
[Response]: 
[Status Code]: 200
[Headers]:
Connection: Keep-Alive
Content-Length: 2336
Content-Type: text/html; charset=UTF-8
Date: Sat, 11 Apr 2020 22:20:14 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.2.34 (Unix) mod_wsgi/3.5 Python/2.7.13 PHP/7.2.10 mod_ssl/2.2.34 OpenSSL/1.0.2o DAV/2 mod_fastcgi/mod_fastcgi-SNAP-0910052141 mod_perl/2.0.9 Perl/v5.24.0
X-Powered-By: PHP/7.2.10
[Response Body]: 
<br />
<b>Notice</b>:  Undefined index: IOS_MCMS_REQUEST in <b>/Applications/MAMP/htdocs/sites/mcms/api.php</b> on line <b>41</b><br />
[Data]: 2336 bytes
[Network Duration]: 0.15002000331878662s
[Serialization Duration]: 0.00012154097203165293s
[Result]: failure(Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))

在输出中你可以看到没有得到 JSON 但一个 PHP 错误说我的 POST 参数不存在。

希望有人能帮助我:)

我找到了解决问题的方法,我将 encoding: JSONEncoding.default 更改为 encoder: URLEncodedFormParameterEncoder(destination: .httpBody)

请求函数现在看起来像这样

AF.request(urlPath, method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody)).responseJSON { (response) in

//some code

}