使用Alamofire

时间:2017-07-03 06:22:57

标签: arrays json swift3 alamofire

所以我正在使用一个应用程序的API来帮助我存储数据,用于将数据发送到用户存储/选择的API的事件,然后获取ID以便稍后引用。 这是我使用的一些代码。

API接受的JSON

    {
   "topic":"test shedule",
   "setdate":"21-09-2017",
   "scheduledate":"22-09-2017",
   "settime":"09:00:00",
   "scheduletime":"10:00:00",
   "agenda":"hi this is test agenda",

   "adminname":"name",
   "type":"meeting",
    "users": "[{\"category\":\"optional\",\"email\":\"abc@gmail.com\"}]",
   "adminemail":"abc@gmail.com"
 }

使用Alamofire发送数据 \

let parameters: Parameters = [
            "topic":topicTextField.text!,
            "setdate":currentDate as String,
            "scheduledate":setDate as String,
            "settime":currentTime as String,
            "scheduletime":setTime as String,
            "agenda":agendaTextField.text!,
            "adminname":"abcname",
            "type":"meeting",
            "users" : "\(smembers)",
            "adminemail":"abc@gmail.com"
        ]

        Alamofire.request("\(baseURL)meeting_shedule.php",method: .post, parameters: parameters).responseJSON { response in
            if let dict = response.result.value as? Dictionary<String, AnyObject> {
                let topic = dict["topic"] as? String
                let g_id = dict["g_id"] as? String

                self.storeMeeting(topic: topic!, g_id: g_id!)

            }
        }

smembers是从词典selectedMembers创建的数组,而词典selectedMembers来自不同的ViewController,使用prepare for segue

    var selectedMembers = [String: String]()
    var smembers = [Any]()
    var selected = [String: String]()

if selectedMembers.isEmpty == false {
            for (key, value) in selectedMembers {
                selected = ["email":key, "category":value]
                smembers.append(selected)
            }
        }

问题

我面临来自api的失败回应。 我认为问题是将“用户”发送到API,因为API要求以字符串形式提供数据并且我发送了一个数组我甚至试图通过序列化将smembers转换为jsonstring但仍然返回失败来解决这个问题。

错误图片我接收 enter image description here

当我通过这样的帖子发送请求时,api正常工作。 enter image description here

我不知道如何解决这个问题,如何发送API将接受的数据。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

如下所示更改逻辑

  var selectedMembers = [String: String]()
    var smembers = [String]()
    var selected = ""

if selectedMembers.isEmpty == false {
            for (key, value) in selectedMembers {
                selected = String(format: "{\"\\email\\\":\"\\%@\"\\,\"\\category\"\\:\"\\%@\"\\}", arguments: [key,value])
                smembers.append(selected)
            }
        }

然后在你的帖子数据

let parameters: Parameters = [
            "topic":topicTextField.text!,
            "setdate":currentDate as String,
            "scheduledate":setDate as String,
            "settime":currentTime as String,
            "scheduletime":setTime as String,
            "agenda":agendaTextField.text!,
            "adminname":"abcname",
            "type":"meeting",
            "users" :"[\(smembers.joined(separator: ","))]",
            "adminemail":"abc@gmail.com"
        ]