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

时间:2018-02-24 07:29:40

标签: swift post alamofire

我使用的是基于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 as 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

1 个答案:

答案 0 :(得分: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()
 }

=>发送此索引作为请求。