Sending json object in GET request in swift in Alamofire

▼魔方 西西 提交于 2019-12-23 13:12:33

问题


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??


回答1:


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



回答2:


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




回答3:


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)


来源:https://stackoverflow.com/questions/39018192/sending-json-object-in-get-request-in-swift-in-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!