Search code examples
jsonswiftpostalamofire

Send POST request with JSON object and query param to REST webservice using alamofire


I'm trying to send POST request to REST webservice using alamofire

I'm passing json object as POST body, and i'm getting the response and everything works fine till now

Alamofire.request(.POST, path, parameters: createQueryParams(), encoding: .JSON)
            .responseArray { (request, response, myWrapper, error) in
                if let anError = error
                {
                    completionHandler(nil, error)
                    println("Error in handling request or response!")
                    return
                }
                completionHandler(myWrapper, nil)
        }

private class func createQueryParams() -> [String:AnyObject]{
        var parameters:[String:AnyObject] = [String:AnyObject]()
        parameters["lat"] = lLat!
        parameters["lng"] = lLon!

        if category != nil { // here is the problem
            parameters["category"] = category!
        }

        return parameters
    }

I have a category filter, if there is a value in category variable, i want to send it as QueryParam (should encoding be .URL? but how can i send json object ??)

this code does not work

if category != nil {
            parameters["category"] = category!
        }

How can i do this? Hope I can explain it clearly

Thanks in advance


Solution

  • You could solve it this way:

    let mutableUrlRequest = NSMutableUrlRequest(URL: URL.URLByAppendingPathComponent(path)
    mutableUrlRequest.HTTPMethod = .POST
    let request = Alamofire.ParameterEncoding.URL.encode(mutableUrlRequest, parameters: createQueryParameters()).0
    
    Alamofire.request(request)
    

    However, I would advise you to look into the Router declaration of Alamofire and try this one. With it you can create dynamic requests and all of them are declared in a single file.

    Edit:
    Oh wait you can forget the previous edit the solution is quite simple and you also answered it by yourself. Yes you just have to change the encoding to .URL, you still are able to send json objects, because Alamofire itself decodes then the json object to a string for queryparams.

    Alamofire.request(.POST, path, parameters:createQueryParams(), encoding: .URL).responseArray...
    

    Edit 2:
    Since the first edit did not work, try this:

    let url = NSURL(string: path)!
    let urlRequest = NSURLReqeust(URL: url)
    request.HTTPMethod = "Post"
    let encoding = Alamofire.ParameterEncoding.URL
    let request = encoding.encode(urlRequest, createQueryParams())
    Alamofire.request(request)