Search code examples
swiftalamofirepostmanswifty-json

Trying to Post a dictionary to my backend


I'm trying to Post a Dictionairy to my backend using Alamofire:

This is my code:

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{
            
        }
    })
}

It won't compile because the phoneNumbersDictionairy is not conforming to the expected argument:

enter image description here

The print(json) however is printing exactly what I have in my Postman though. This is the body I want to post. The printed statement:

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

My Postman:

enter image description here

How can I make this happen?


Solution

  • I ended up using this:

    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)
            }
        })
    }