试图将字典发布到我的后端

时间:2016-10-03 09:59:08

标签: swift alamofire postman swifty-json

我试图使用Alamofire将Dictionairy发布到我的后端:

这是我的代码:

func postCheckUserPhonenumbers(phonenumbers:[String], completionHandler: (([AnyObject?], AnyObject?) -> Void)) {
    let urlString = Constant.apiUrl().stringByAppendingFormat(Constant.apiPostCheckUserPhonenumbers)

    let phoneNumbersDictionary = phonenumbers.map({ ["number": $0] })

    let json = JSON(phoneNumbersDictionary)
    print(json)

    Alamofire.request(.POST, urlString, parameters: phoneNumbersDictionary, encoding: .JSON).validate().responseJSON(completionHandler: {response in
        if response.result.isSuccess{
            if let json = response.result.value {
                let json = JSON(json)

            }
        }
        if response.result.isFailure{

        }
    })
}

它不会编译,因为phoneNumbersDictionairy不符合预期的参数:

enter image description here

然而,印刷品(json)印刷的正是我邮差中的印记。这是我要张贴的身体。 印刷声明:

[
  {
    "number" : "85555512"
  },
  {
    "number" : "85551212"
  },
  {
    "number" : "55648583"
  }
]

我的邮差:

enter image description here

我怎样才能实现这一目标?

2 个答案:

答案 0 :(得分:0)

正如错误消息所述,phonenumbers.map({["number": $0]})返回类型为[[String:String]]的数组,正如您在附加的图像上看到的那样。 Playground

Alamorfire期望[String: AnyObejct]?类型的数组作为参数。

但也许How to send a post request with bodySending json array via alamofire可以帮到你。

答案 1 :(得分:0)

我最终使用了这个:

func postCheckUserPhonenumbers(phonenumbers:[String], completionHandler: (([AnyObject?], AnyObject?) -> Void)) {
    let urlString = Constant.apiUrl().stringByAppendingFormat(Constant.apiPostCheckUserPhonenumbers)

    let phoneNumbersDictionary = phonenumbers.map({ ["number": $0] })

    let inputJSON = try? NSJSONSerialization.dataWithJSONObject(phoneNumbersDictionary, options: [])

    let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.HTTPMethod = "POST"
    request.HTTPBody = inputJSON

    Alamofire.request(request).validate().responseJSON(completionHandler: {response in
        if response.result.isSuccess{
            if let value = response.result.value {
                let json = JSON(value)
                let jsonString = json.rawString()
                if let users:Array<User> = Mapper<User>().mapArray(jsonString) {
                    completionHandler(users, nil)
                } else {
                    completionHandler([nil], nil)
                }
            }
        }
        if response.result.isFailure{
            let message = ApiMessage()
            message.message = "No users found"
            completionHandler([nil],message)
        }
    })
}