繁体   English   中英

如何在读取多个参数的 Swift 中发出发布请求?

[英]How can I make a post request in Swift that reads more than 1 parameter?

I am trying to send a body of JSON to a REST API, but it is only reading the first parameter and not recognizing the rest of the JSON at all. 我测试了错误输入 JSON 主体的其他部分,但我没有像往常一样收到错误。

func postRequest(classroomID: String, email: String, vote: String){

    //declare parameter as a dictionary which contains string as key and value combination.
    let parameters = [
            "classroomID": classroomID,
            "LastUpdated": "2020-01-01",
            "TheVoteData"[
                          "Email": email,
                          "TheVote": vote
              ]
     ]

    //create the url with NSURL
    let url = URL(string: "https://www.api-gateway/dynamoDB/resource")!

    //create the session object
    let session = URLSession.shared

    //now create the Request object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "POST" //set http method as POST

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body
    } catch let error {
        print(error.localizedDescription)
    }

    //HTTP Headers
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request, completionHandler: { data, response, error in

        guard error == nil else {
            completion(nil, error)
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else {
                return
            }
            print(json)
            completion(json, nil)
        } catch let error {
            print(error.localizedDescription)
        }
    })

    task.resume()
}

这会将教室 ID 发布到数据库,但不会发布 email 或投票。 我从这里得到了这个方法: How to make HTTP Post request with JSON body in Swift

非常感谢任何帮助!

编辑:我能够通过配置 API 网关将输入作为简单数组而不是字典数组来解决我的问题。 非常感谢所有花时间帮助我的人!!

我认为您在参数中提供的 JSON 数据无效(我使用 jsonlint.com 检查)试试这个:

func postRequest(classroomID: String, email: String, vote: String){

//declare parameter as a dictionary which contains string as key and value combination.
let parameters: [String:Any] = [
        "classroomID": classroomID,
        "LastUpdated": "2020-01-01",
        "TheVoteData":[
                      "Email": email,
                      "TheVote": vote
    ]
 ]

//create the url with NSURL
let url = URL(string: "https://www.api-gateway/dynamoDB/resource")!


//now create the Request object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST

do {
    request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body
} catch let error {
    print(error.localizedDescription)
}

//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: [])
//create dataTask using the session object to send data to the server
 let task = URLSession.shared.uploadTask(with: request, from: jsonData) { data, response, error in
    if let data = data, let dataString = String(data: data, encoding: .utf8) {
        print(dataString)
    }
    //Returns HHTP response if
    if let httpResponse = response as? HTTPURLResponse {
        print(httpResponse.statusCode)
    }
}

task.resume()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM