Sending json object in GET request in fast mode in Alamofire

I am trying to execute a GET requst with a json object attached to it. It's me how I created a JSON object

   let jsonObject: [String: AnyObject] = [

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

and then I fulfilled the request

like this

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

but this gave me an error that binds the URL to an invalid character

so I encoded the url from this

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

this will encode the url, but again I will give me the following error

Error request: Error Domain = NSCocoaErrorDomain Code = 3840 "Invalid value around character 0." UserInfo = {NSDebugDescription = Invalid value around character 0.}

so my question is how to associate a json object with a GET URL?

+4
source share
3 answers

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)")
}
+1

:

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
}

:

Alamofire.request(encode(json))

, :)

0

, :

  • Add a parameter to the end of the URL string
  • Passing parameters to an Alamofire request

As you make a request GET, your parameters should be encoded anyway, since GET requests should not have a body. Why don't you just add your request filtersto the parameters?

let parameters: [String: AnyObject] = [

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

Alamofire.request(.GET, Constant.WebClient.WS_URL + "/product", parameters: parameters)
0
source

Source: https://habr.com/ru/post/1651671/


All Articles