如何在Swift的JSON POST方法中传递键值参数?

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

这是API http:/itaag-env-1.ap-south-1.elasticbeanstalk.comfiltertaggedusers。

其参数: "contactsList" : ["5987606147", "6179987671", "5082508888"]

其头: ["deviceid". "584D97F-761A-4C24-8C4B-C145A8B8BD75","userType": "584D97F-761A-4C24-8C4B-C145A8B8BD75","用户类型"。"personal", "key": "9609cc826b0d472faf9967370c095c21"]

在我的代码中,如果我放了断点,那么 filtertaggedUser() 呼叫,但我无法进去 完工处理程序 门禁不入 dataTask

为什么api能正常工作。

我试图在URL字符串中传递参数键值,如下图所示

 let urlStr  = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/?contactsList=" + "8908908900"

这是正确的方法吗?

以上API的代码。

 func filtertaggedUser() {
    print("inside filter taggedusers")

    let headers = ["deviceid": "584D97F-761A-4C24-8C4B-C145A8B8BD75", "userType": "personal", "key": "9609cc826b0d472faf9967370c095c21"]
    let urlStr  = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/?contactsList=" + "8908908900"
    let request = NSMutableURLRequest(url: NSURL(string:urlStr)! as URL,cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
    request.httpMethod          = "POST"
    request.allHTTPHeaderFields = headers
    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in

            // access not coming here
            let httpResponse = response as? HTTPURLResponse
            if httpResponse!.statusCode == 200 {
                print("filter taggedusers inside")

                do {
                    print("filter taggedusers inside do")

                    let jsonObject  = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String :AnyObject]
                    print("filter taggedusers \(jsonObject)")


                } catch { print(error.localizedDescription) }
            } else { Constants.showAlertView(alertViewTitle: "", Message: "Something went wrong, Please try again", on: self) }

    })
    dataTask.resume()
}

OUTPUT:

POSTMAN OUTPUT

POSTMAN车身

为什么没有响应,我在哪里做错了,请帮我看看代码。

ios json swift post
1个回答
0
投票

我们可以调用 Post 请求API如下。

func getPostString(params:[String:Any]) -> String
    {
        var data = [String]()
        for(key, value) in params
        {
            data.append(key + "=\(value)")
        }
        print(data.map { String($0) }.joined(separator: "&"))
        return data.map { String($0) }.joined(separator: "&")
    }

    func callPostApi(){
        let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")
        guard let requestUrl = url else { fatalError() }
        var request = URLRequest(url: requestUrl)
        request.httpMethod = "POST"

        request.setValue("584D97F-761A-4C24-8C4B-C145A8B8BD75", forHTTPHeaderField: "deviceid")
        request.setValue("9609cc826b0d472faf9967370c095c21", forHTTPHeaderField: "key")
        request.setValue("personal", forHTTPHeaderField: "userType")


        let parameters = getPostString(params:   ["contactsList":["8908908900"]])
        request.httpBody = parameters.data(using: .utf8)
        // Perform HTTP Request
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
                let httpResponse = response as? HTTPURLResponse
                print(httpResponse!.statusCode)
                // Check for Error
                if let error = error {
                    print("Error took place \(error)")
                    return
                }

                // Convert HTTP Response Data to a String
                if let data = data, let dataString = String(data: data, encoding: .utf8) {
                    print("Response data string:\n \(dataString)")
                }
        }
        task.resume()
    }

产量 :

{"8908908900":{"userId":"9609cc826b0d472faf9967370c095c21","userName":"Satish Madhavarapu","profilePic":null,"oniTaag":true,"tagged":false,"userType":"personal"}}
© www.soinside.com 2019 - 2024. All rights reserved.