Alamofire POST参数未通过

问题描述 投票:0回答:1

我想将发帖请求发送到我的网站。但看来我的POST请求没有通过。

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

// just to check incomming 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文件,其中包含用于发送发布请求的代码

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参数不存在。

我希望有人可以帮助我:)

ios json swift post alamofire
1个回答
0
投票

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

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

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

//some code

}
© www.soinside.com 2019 - 2024. All rights reserved.