Alamofire发布请求将数据作为数组发送

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

我正在使用基于php的Web服务,它接受post变量。当我在postman中运行它时工作正常但是当我在我的代码中从Alamofire运行它时,web dev表示他正在接收数组中的请求。以下是服务器收到的请求:

{ “{\” gameDate \ “:\” 2018-03-31_12:43:37 \ “\ ”gameFee \“:\ ”55 \“,\ ”gameInstruction \“:\ ”\“ \” gametitle \ “:\” TTT \”,\ “键\”:\ “AAAA \”,\ “纬度\”:\ “\”,\ “经度\”:\ “\”,\ “numOfPlayers \”:20, \ “隐私\”:0,\ “状态\”:0,\ “UID \”:\ “AAAAA \”} “:””, “0”: “”}

以下是我在Alamofire发送请求的方式:

Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: ["Content-Type":"application/x-www-form-urlencoded"]).responseJSON {
        response in
        switch response.result {
        case .success:
            completionHandler(Result.Success(response.result.value))
            break
        case .failure(let error):
            print(error)
            completionHandler(Result.Failure(.serverConnectionFailure))
        }
    }

PARAM:

[“key”:appKey为AnyObject,“uid”:event.uid为AnyObject,“gametitle”:event.gameTitle为AnyObject,“gameDate”:event.gameDate为AnyObject,“gameFee”:event.gameFee为AnyObject,“ gameInstruction“:event.gameInstruction as AnyObject,”latitude“:event.latitude as AnyObject,”longitude“:event.longitude as AnyObject,”numOfPlayers“:event.numOfPlayers as AnyObject,”privacy“:event.privacy as AnyObject,” status“:event.status as AnyObject]

我该如何将其转换为php服务接受的普通键值请求?

编辑:我的邮递员请求有效:enter image description here

swift post alamofire
1个回答
0
投票

你必须以字典的形式发送参数(即[String:Any])。

要将类转换为[String:Any]: -

//Protocol for converting Class to Dictionary
protocol JSONAble {}

extension JSONAble {

    func toDict() -> [String : Any] {
        var dict = [String : Any]()
        let otherSelf = Mirror(reflecting: self)
        for child in otherSelf.children {
            if let key = child.label {
                dict[key] = child.value
            }
        }
        return dict
    }
}

//Request Parameters Class
class request : JSONAble {

    //MARK:- Properties
    var gameDate = String()
    var gameFee = String()
    var gameInstruction = String()
    .
    .

    //MARK:- Constructor
    init(gameDate : String?, gameFee: String?, gameInstruction: String?) {        
        self.gameDate = gameDate
        self. gameFee = gameFee
        self. gameInstruction = gameInstruction
    }
}

使用:-

var params : [String : Any]?

if let jsonableRequest = request as? JSONAble {
        params = jsonableRequest.toDict()
 }

=>发送此params作为请求。

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