Construction was too complex to be solved in reasonable time - ios

I have problem with Swift 3, I am trying to send a request to a server and get JSON, but I get:
Construction was too complex to be solved in reasonable time.
I tried every way, but it doesn't worked.
var userName = "root"
var password = "admin01"
//var LOGIN_TOKEN = 0000000000000000
let parameters = [
"{\n",
" \"jsonrpc\": \"2.0\",\n",
" \"id\": \"1\",\n",
" \"method\": \"call\",\n",
" \"params\": [\n",
" \"0000000000000000\",\n",
" \"session\",\n",
" \"login\",\n",
" {\n",
" \"username\": \"" + userName + "\",\n",
" \"password\": \"" + password + "\"\n",
" }\n",
" ]\n",
"}"
]
let joiner = ""
let joinedStrings = parameters.joined(separator: joiner)
print("joinedStrings: \(joinedStrings)")
// All three of these calls are equivalent
Alamofire.request("http://192.168.1.1", method: .post, parameters: parameters).responseJSON { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Now I tryed to creat dic and convert to Json, but after that, I get problem on request there I declare my parameters. they say: use of unresolved identifier dictFromJSON
var userName = "root"
var password = "admin01"
//var LOGIN_TOKEN = 0000000000000000
let jsonObject: [String: Any] =
["jsonrpc" : 2.0,
"id": 1,
"method": "call",
"params": [ "00000000000000",
"session",
"login",
[ "username": userName,
"password": password]],
]
do {
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
// All three of these calls are equivalent
Alamofire.request("http://192.168.1.1/ubus", method: .post, parameters: dictFromJSON).responseJSON { response in
print("Request: \(response.request)")
print("Response: \(response.response)")

UPDATED:
According to the document of Alamofire, (you can see here), you don't need to convert the parameters Dictionary to JSON.
For example,
let parameters: Parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
"x": 1,
"y": 2,
"z": 3
]
]
// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/post", parameters: parameters)
Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.httpBody)
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
OLD:
You should use Dictionay for the parameter actually.
Therefore, instead of declaring the parameter like you did, you should do like this:
let parameters = ["jsonrpc" : 2.0,
"id": 1,
"method": "call",
"params": [ "00000000000000",
"session",
"login",
[ "username": userName,
"password": password]],
]

Related

How to Arrangement array before send request to alamofire in swift

let request = NSMutableDictionary()
request.setDictionary([ "merchant_reference":getRandomMerchant, "merchant_identifier":"e54638eb", "access_code":"hRRVGXrIpHSYoH19Ebwt", "signature": base64Str, "service_command":"OTP_GENERATE", "language":"en", "payment_option":"VALU", "phone_number":"01008606003", "merchant_order_id":getRandomMerchant, "amount":getTotal, "currency":"EGP", "products":[ [ "product_name": getName, "product_price": getTotal, "product_category":getProductType ] ] ])
Alamofire.request(URLAPi.URL_Payment_Api ,
method : .post ,
parameters : (request as! Parameters) ,
encoding: JSONEncoding.default
).responseJSON { (response) in
debugPrint(response)
if response.result.isSuccess {
let jsonpayfortrequest : JSON = JSON(response.result.value!)
var resultsArray = jsonpayfortrequest.arrayValue
var sortedResults = resultsArray.sorted { $0.stringValue > $1.stringValue }
print(jsonpayfortrequest)
print(resultsArray)
print(sortedResults)
print(jsonpayfortrequest.sorted(by: {$0 > $1}))
let passobjectforrootclasspayfort = OTPGenrateModel(fromJson: jsonpayfortrequest)
print(passobjectforrootclasspayfort.transaction_id!)
SVProgressHUD.dismiss()
} else {
print("error connection") SVProgressHUD.dismiss()
}
}
Try this way, Hope, that will fixe your issue. If it doesn't, please reply
let parameters: [String: Any] = [
"merchant_reference":getRandomMerchant,
"merchant_identifier":"e54638eb",
"access_code":"hRRVGXrIpHSYoH19Ebwt",
"signature": base64Str,
"service_command":"OTP_GENERATE",
"language":"en",
"payment_option":"VALU",
"phone_number":"01008606003",
"merchant_order_id":getRandomMerchant,
"amount":getTotal,
"currency":"EGP",
"products": [
[
"product_name": getName,
"product_price": getTotal,
"product_category":getProductType
]
]
]
Alamofire.request(URLAPi.URL_Payment_Api , method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
// Insert your code here
}

post array of json with alamofire swift

How can i post array of json objects with alamofire in swift?
my final data (which i want to post) looks like:
temp = [{
"time": 1,
"score": 20,
"status": true,
"answer": 456
},
{
"time": 0,
"score": 0,
"status": false,
"answer": 234
},
{
"time": 0,
"score": 20,
"status": true,
"answer": 123
}
]
i got hint that i have to create custom parameter encoding but i am confused how can i do that. Someone please help me.
my current code looks like
let parameters: Parameters = [
"answers": temp,
"challenge_date": "2019-03-01"
]
Alamofire.request("...url", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseJSON {
response in
if
let status = response.response ? .statusCode {
let classFinal: JSON = JSON(response.result.value!)
if (status > 199 && status < 300) {
self.dismiss(animated: true)
} else {
}
}
}
In your code change method .put to .post, and not required to SVProgressHUD.dismiss() in else, because you already dismiss before if else part
Also, you need to convert your JSON string(temp variable) to array and then pass with the parameter.
let parameters: Parameters = [
"answers": temp,
"challenge_date": "2019-03-01"
]
Alamofire.request("...url", method: .post, parameters: parameters, encoding: JSONEncoding.default , headers: headers)
.responseJSON { response in
if let status = response.response?.statusCode {
let classFinal : JSON = JSON(response.result.value!)
SVProgressHUD.dismiss()
if status > 199 && status < 300 {
self.dismiss(animated: true)
}
}
}
I hope your Parameters class follows Codable protocol.
As far as I see, you are getting an error parsing that object to JSON. Hence that is the source of your error.
Could you also add code for your Parameters class / struct
First, convert your Temp
Array into String
than pass in that in parameters of Alamofire.
extension NSArray {
func toJSonString(data : NSArray) -> String {
var jsonString = "";
do {
let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
} catch {
print(error.localizedDescription)
}
return jsonString;
}
}

Converting Dictionary to Json to pass parameters in Alamofire

I have a dictionary with key as username and value as email. Which i would like to send to an api using Alamofire i have no clue how to approach this problem as i am suppose to send multiple users to the api to save at once.
Dictionary
var selectedMembers = [String: String]()
The data saved in this dictionary is appended in a different VC from a table view where we can choose how many users we want to append in the dictionary.
Now i need to convert this dictionary into json formate to send to the api through alamofire.
Json Formate
"users": [
{
"user_email": "abc#gmail.com",
"user_name": "abc"
},
{
"user_email": "abc2#gmail.com",
"user_name": "abc2"
}
]
Alamofire Code
let parameters: Parameters = [
"users" : [
[
"user_name" : "user_name goes here",
"user_email" : "user_email goes here"
]
]
]
Alamofire.request("\(baseURL)", method: .post, parameters: parameters).responseJSON { response in
}
How i solved the Problem
i created a function that prints the the data how i want it and placed it in Alamofire parameters something like this.
var selectedMembers = [String: String]()
var smembers = [AnyObject]()
var selected = [String: String]()
if selectedMembers.isEmpty == false {
for (key, value) in selectedMembers {
selected = ["useremail": key, "catagory": value]
smembers.append(selected as AnyObject)
}
}
let jsonData = try? JSONSerialization.data(withJSONObject: smembers, options: JSONSerialization.WritingOptions())
let jsonString = NSString(data: jsonData!, encoding: String.Encoding.utf8.rawValue)
let parameters: Parameters = [
"users" : jsonString as AnyObject
]
Alamofire.request("\(baseURL)", method: .post, parameters: parameters).responseJSON { response in
}
You just need to make Array of dictionary(user) as of currently you are setting user's value as Dictionary instead of Array.
let parameters: Parameters = [
"users" : [
[
"user_name" : "abc",
"user_email" : "abc#gmail.com"
],
[
"user_name" : "abc2",
"user_email" : "abc2#gmail.com"
]
]
]
Alamofire.request("\(baseURL)", method: .post, parameters: parameters).responseJSON { response in
}
If your web API demands the post data to send in JSON format then below written method is a way to do this.
func calltheAPIToSendSelectedUser () {
let parameters: [String: Any] = [
"users" : [
[
{
"user_name" : "user1_name goes here",
"user_email" : "user1_email goes here"
},
{
"user_name" : "user2_name goes here",
"user_email" : "user2_email goes here"
},
{
"user_name" : "user3_name goes here",
"user_email" : "user3_email goes here"
},
]
]
]
var request = URLRequest(url: URL(string: "YourApiURL")!)
request.httpMethod = "POST"
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: [.prettyPrinted])
Alamofire.request(request).responseJSON { response in
}
}
Here's my solution that worked for invoking POST using Alamofire and passing in an array of dictionary values as the Parameters arg.
Notice the 'User' key which contains a dictionary of values.
let dict: NSMutableDictionary = [:]
dict["facebook_id"] = "1234559393"
dict["name"] = "TestName"
dict["email"] = "TestEmailID"
let params: Parameters = [
"user": dict
]
Alamofire.request("YOURURL", method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON(completionHandler: { (response) in
switch response.result {
case .success:
print("succeeded in making a Facebook Sign up REST API. Now going to update user profile"
break
case .failure(let error):
return
print(error)
}
})
Right at the point where you are adding items to the dictionary, is where you can check for nil values and avoid adding as needed, thus making it dynamic.

Swift Alamofire migration parsing JSON

On migrating to recent versions am finding it hard to get and print the fields of name, age, and dob from JSON using Alamofire 4 parsing in Swift 3.
JSON FORMAT
"SetValues": {
"data":
[
{
"Name": yyyyy ,
"Age": 13,
"DOB": "2017-06-08",
}
{
"Name": xxxx ,
"Age": 33,
"DOB": "2015-06-08",
}
]
}
I tried
Alamofire.request(url!,
method: .post,
parameters: nil,
encoding: JSONEncoding.default,
headers: headers)
.responseJSON{ response in
let datamsg = jsonmsg?["SetValues"] as? [String : Any]
let dataset = datamsg?["data"] as? [String : Any]
let setValues = datamsg?["data"]
print (setValues[0]["Name"] as Any)
}
The problem is in this line
let dataset = datamsg?["data"] as? [String : Any]
as seen from the JSON response string it should be like below
let dataset = datamsg?["data"] as? [[String : Any]]
let name = dataset?[0]["Name"] as? String

URL Encode Alamofire GET params with SwiftyJSON

I am trying to have Alamofire send the following parameter in a GET request but it's sending gibberish:
filters={"$and":[{"name":{"$bw":"duke"},"country":"gb"}]}
//www.example.com/example?filters={"$and":[{"name":{"$bw":"duke"},"country":"gb"}]}
//Obviously URL encoded
This is my code:
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
print(json)
outputs
{
"$and" : [
{
"name" : {
"$bw" : "duke"
},
"country" : "gb"
}
]
}
This is my params request:
let params = ["filters" : json.rawValue, "limit":"1", "KEY":"my_key"]
This is what AlamoFire is sending:
KEY=my_key&
filters[$and][][country]=gb&
filters[$and][][name][$bw]=duke&
limit=1
As you can see the filter parameter is a complete mess. What am I doing wrong?
By default Alamofire encodes the parameters using Parameter List in the POST body. Try changing the encoding to JSON. This way Alamofire will serialize the dictionary as a JSON string as you expect:
let parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
Or using your code:
let string = "duke"
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
let params = ["filters" : json.rawValue, "limit":"1", "KEY":"my_key"]
Alamofire.request(.POST, "http://httpbin.org/post", parameters: params, encoding: .JSON)
.responseString(encoding: NSUTF8StringEncoding) { request, response, content, error in
NSLog("Request: %# - %#\n%#", request.HTTPMethod!, request.URL!, request.HTTPBody.map { body in NSString(data: body, encoding: NSUTF8StringEncoding) ?? "" } ?? "")
if let response = response {
NSLog("Response: %#\n%#", response, content ?? "")
}
}
Gets the output:
Request: POST - http://httpbin.org/post
{"filters":{"$and":[{"name":{"$bw":"duke"},"country":"gb"}]},"limit":"1","KEY":"my_key"}
EDIT: URL-Encoded JSON in the GET parameters
If you want to send a URL-Encoded JSON in the GET parameters you have to generate first the JSON string and then pass it as a string in your parameters dictionary:
SWIFT 1
let string = "duke"
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
// Generate the string representation of the JSON value
let jsonString = json.rawString(encoding: NSUTF8StringEncoding, options: nil)!
let params = ["filters" : jsonString, "limit": "1", "KEY": "my_key"]
Alamofire.request(.GET, "http://httpbin.org/post", parameters: params)
.responseString(encoding: NSUTF8StringEncoding) { request, response, content, error in
NSLog("Request: %# - %#\n%#", request.HTTPMethod!, request.URL!, request.HTTPBody.map { body in NSString(data: body, encoding: NSUTF8StringEncoding) ?? "" } ?? "")
if let response = response {
NSLog("Response: %#\n%#", response, content ?? "")
}
}
SWIFT 2
let string = "duke"
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
// Generate the string representation of the JSON value
let jsonString = json.rawString(NSUTF8StringEncoding)!
let params = ["filters" : jsonString, "limit": "1", "KEY": "my_key"]
Alamofire.request(.GET, "http://httpbin.org/post", parameters: params)
.responseString(encoding: NSUTF8StringEncoding) { request, response, result in
NSLog("Request: %# - %#\n%#", request!.HTTPMethod!, request!.URL!, request!.HTTPBody.map { body in NSString(data: body, encoding: NSUTF8StringEncoding) ?? "" } ?? "")
switch result {
case .Success(let value):
NSLog("Response with content: %#", value)
case .Failure(let data, _):
NSLog("Response with error: %#", data ?? NSData())
}
}
SWIFT 3 and Alamofire 4.0
let string = "duke"
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
// Generate the string representation of the JSON value
let jsonString = json.rawString(.utf8)!
let params = ["filters" : jsonString, "limit": "1", "KEY": "my_key"]
Alamofire.request("http://httpbin.org/post", method: .get, parameters: params)
.responseString { response in
#if DEBUG
let request = response.request
NSLog("Request: \(request!.httpMethod!) - \(request!.url!.absoluteString)\n\(request!.httpBody.map { body in String(data: body, encoding: .utf8) ?? "" } ?? "")")
switch response.result {
case .success(let value):
print("Response with content \(value)")
case .failure(let error):
print("Response with error: \(error as NSError): \(response.data ?? Data())")
}
#endif
}
This generates a GET request with the following URL:
http://httpbin.org/post?KEY=my_key&filters=%7B%22%24and%22%3A%5B%7B%22name%22%3A%7B%22%24bw%22%3A%22duke%22%7D%2C%22country%22%3A%22gb%22%7D%5D%7D&limit=1
That URL-Decoded is:
http://httpbin.org/post?KEY=my_key&filters={"$and":[{"name":{"$bw":"duke"},"country":"gb"}]}&limit=1

Resources