【问题标题】:Alamofire post request sending data as arrayAlamofire 发布请求以数组形式发送数据
【发布时间】:2018-08-04 06:05:03
【问题描述】:

我正在使用基于 php 的 web 服务,它接受 post 变量。当我在邮递员中运行它时,它工作正常,但是当我在代码中从 Alamofire 运行它时,网络开发人员说他正在接收数组中的请求。以下是服务器收到的请求:

{"{\"gameDate\":\"2018-03-31_12:43:37\",\"gameFee\":\"55\",\"gameInstruction\":\"\",\ "游戏标题\":\"ttt\",\"key\":\"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))
        }
    }

参数:

["key":appKey as AnyObject, "uid":event.uid as AnyObject,"gametitle":event.gameTitle as AnyObject,"gameDate":event.gameDate as 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服务接受的普通键值请求?

编辑: 我的邮递员请求有效:

【问题讨论】:

    标签: swift post alamofire


    【解决方案1】:

    您必须以字典的形式发送参数(即 [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()
     }
    

    => 将此参数作为请求发送。

    【讨论】:

    • 我试过了,网络服务仍然收到同样的请求
    • 调试和检查,是否将类转换为[String:Any]?
    • 它被转换了,我已经检查过了,只是请求在服务器以不同的方式接收。
    • 在 pratyushpratik@hotmail.com 向我发送请求、标头和网址
    猜你喜欢
    • 2022-08-06
    • 1970-01-01
    • 2020-09-30
    • 2022-01-06
    • 1970-01-01
    • 2017-05-15
    • 2016-08-02
    • 2015-10-25
    • 2017-05-04
    相关资源
    最近更新 更多