4

I'm trying to execute a GET requst with json object binded to it , This i how i generated JSON object

   let jsonObject: [String: AnyObject] = [

        "ean_code": [
            "type": "match",
            "value": "16743799"
        ]
    ]

and then I executed the request

like this

        Alamofire.request(.GET,Constant.WebClient.WS_URL + "/product?filters="+String(jsonObject),parameters:parameters)

but this gave me an error which is canot bind the URL with invalid character

so i encoded the URL from this

let request = String(jsonObject).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPasswordAllowedCharacterSet())!

this will encode the URL but i again this will give me following error

Request failed with error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

so my question is how can I bind a json object to GET URL??

Mr.G
  • 1,275
  • 1
  • 18
  • 48

3 Answers3

3

Do something like this

let parameters: [String: AnyObject] = [

    "filters": "merchantName",
    "ean_code": [
        "type": "match",
        "value": "16743799"
    ]
]

do {
    let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: .PrettyPrinted)
    let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
    let urlEncodedJson = jsonString!.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
    let urlString = "http://www.filter.com/&params=\(urlEncodedJson!)"
    let url = NSURL(string: urlString)
    // Trigger alaomofire request with url
}
catch let JSONError as NSError {
    print("\(JSONError)")
}
hariszaman
  • 8,202
  • 2
  • 40
  • 59
  • I would still say, don't send json object in url but rather, use a post/put request to do that. – hariszaman Aug 19 '16 at 17:42
  • i complete agree with u . but the Backend developed from larevel and seems it has the capability to send params in GET, – Mr.G Aug 21 '16 at 02:48
0

Try:

func encode(json: [String: AnyObject]) -> NSMutableURLRequest {
    let request: NSMutableURLRequest = ...
    if let URLComponents = NSURLComponents(URL: request.URL!, resolvingAgainstBaseURL: false) {
    let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(json)
    URLComponents.percentEncodedQuery = percentEncodedQuery
    request.URL = URLComponents.URL
    return request
}

func query(parameters: [String: AnyObject]?) -> String {
    guard let parameters = parameters else {
        return ""
    }
    var components: [(String, String)] = []

    for key in parameters.keys.sort(<) {
        let value = parameters[key]!
        components += queryComponents(key, value)
    }

    return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")
}

func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
    var components: [(String, String)] = []

    if let dictionary = value as? [String: AnyObject] {
        for (nestedKey, value) in dictionary {
            components += queryComponents("\(key)[\(nestedKey)]", value)
        }
    } else if let array = value as? [AnyObject] {
        for value in array {
            components += queryComponents("\(key)[]", value)
        }
    } else {
        components.append((key, "\(value)"))
    }

    return components
}

Use it as:

Alamofire.request(encode(json))

It is just code snipets, so you will have to place it in proper place :)

Daniel Sumara
  • 2,234
  • 20
  • 25
0

It looks like you are trying to add query parameters in two ways:

  • Adding a parameter to the end of you URL string
  • By passing parameters into the Alamofire request

As you are doing a GET request, your parameters should all be URL encoded anyway, as GET requests shouldn't have a body. Why don't you just add your filters query into the parameters?

let parameters: [String: AnyObject] = [

    "ean_code": [
        "type": "match",
        "value": "16743799"
    ]
]

Alamofire.request(.GET, Constant.WebClient.WS_URL + "/product", parameters: parameters)
tebs1200
  • 1,205
  • 12
  • 19
  • i have edited the question please check now , merchant name is not the correct parameter – Mr.G Aug 18 '16 at 16:36
  • I've updated my answer. You don't need to 'manually' append the parameters to your url. The `parameters` argument is designed to encode the parameters and do that for you. – tebs1200 Aug 19 '16 at 00:12
  • 1
    Can you please provide an example of what the query string should look like? What is the server expecting? Once we see that we should be able to help you construct it – tebs1200 Aug 19 '16 at 02:18
  • %7B%22ean_code%22%3A%7B%22type%22%3A%22match%22%2C%22value%22%3A%2216743799%22%7D%7D this shoud be the json format that should appen in to filter parameter i tested this with swagger – Mr.G Aug 19 '16 at 16:41