问题
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/¶ms=\(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