Unable to parse JSON response object Alamofire - ios

I am making a post request and get back a JSON response in the form of [Object object]. I tried various ways to parse this JSON but wasn't able to. Whenever I try, I get an error saying Could not cast value of type '__NSCFString' (0x10f3dc4a0) to 'NSData'
On the backend side, I have a NodeJS server that replies with res.send. Do I need to convert this data to something else or is there a way I can parse this JSON Data and get the Dictionary object that I am originally supposed to get. I'm using Swift 3 with Alamofire 4.0.
How can I solve this issue?
This is my request code in iOS
Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
debugPrint(response)
let data_temp = try! JSONSerialization.jsonObject(with: response.result.value! as! Data, options: JSONSerialization.ReadingOptions.mutableContainers)
print(data_temp)
}
}

Related

Pass JSON object in GET request: iOS

I want to add the JSON object in GET request with URL. Please refer below URL.
https://testdata.com/xyz/&form={"id":"12", "data": "3"}
I am getting nil while converting String to URL
let serviceUrl = URL(string: url)
Thanks in advance.
I was already tried below solution but unfortunately no luck.
JSONSerialization.data
converting to string with utf8
removed whitespaces if any
addingPercentEncoding with URL host allowed
It's not recommended, to send a request body with GET request. GET request means to fetch all the resources/content that this URL has to offer. If they are parsing the GET body on server side, it's against the semantics. But if you really need to do it. Use Almofire. Here's a Sample Code.
let parameters : [String : Any] = [
"id":"12",
"data":"3"
]
func getContent(parameters: [String: Any]) {
Alamofire.request("http://18.218.235.193:3000/user/securedtoken", method:
.get, parameters: parameters, encoding: JSONEncoding.default)
.responseObject {(response:
DataResponse<YOUR RESPONSE MODEL HERE>) in
let response = response.result.value
//Do Something (Success)
}
}
I recommend you to use Alamofire library. You can do what you want using following code snippet
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["form": ["id": 12, "data": 3]])
.response { request, response, data, error in
print(request)
print(response)
print(error)
}

How to send empty JSON via Alamofire?

How can i pass an empty JSON string to Alamofire and send POST request?
I tried like this:
let lazyPojo = LazyPojo()
let JSONString = Mapper<LazyPojo>().map(lazyPojo)
Alamofire.request(.POST, url, JSONString, encoding:.JSON).validate()
.responseJSON{...}
It says that my JSONString have to be Unwrapped, but when i run it i got this error: fatal error: unexpectedly found nil while unwrapping an Optional value.
How is this possible?
I think you didn't mention parameter name. So check this one :-
Alamofire.request(.POST, url, parameters: ["parameters": "\(JSONString)"])
.validate()
.responseJSON { }

Printing data in Alamofire request

I am trying to print the data returned from an alamofire post request in swift like so:
Alamofire.request(.POST, "http://blablabla.com/test1", parameters: ["operand1": "123"]).response { request, response, data, error in
print(request)
print(response)
print(data, radix: 16)
print(error)
}
but when I try to print data it doesn't print a string a string, instead it prints:
<796570>
I am a bit new to swift so I don't really know if there is a way or a reason for this.
That is the raw server response which is in NSData type. You can make use of some built-in serializers such as .responseString() in order to convert that into user readable value:
Alamofire.request(.POST, "http://blablabla.com/test1", parameters: ["operand1": "123"]).responseString { response in
print("Response String: \(response.result.value)")
}
You can check out other serializers in the Alamofire documentation.

Post json encode parameter swift

Can you suggest me how to pass following parameter in swift or objective c
let parameters = ["Access_Key":"0699DADD8A2B5FC2E8FF6FF5DDFE03EEDB3ED2132B29EA4F28","Packages":["Length":self.Length,"Type":"","Kg":self.Weight,"Height":self.Height,"Width":self.Width,"Name":self.SkuName],
"issignaturerequired":"true",
"Outputs":["LABEL_PNG_100X175"],
"DeliveryReference":"86882",
"Destination":["ContactPerson":self.CustomerFirstname,"Address":["PostCode":self.PostalCode,"StreetAddress":self.Address1,"Suburb":self.City,"BuildingName":"","City":self.City,"CountryCode":"AU"],"PhoneNumber":"","Email":self.CustomerEmail,"Name":self.CustomerFirstname],
"PrintToPrinter":"true",
"SendTrackingEmail":"",
"Commodities":["UnitKg":"1.0000","Currency":"NZD","Country":"NZ","Units":"1","Description":"Drums Drum Accessories Drum Bags","UnitValue":"44.0"],
"DeliveryInstructions":"None"
]
Alamofire.request(.POST, "http://api.omniparcel.com/labels/printcheapestcourier",parameters: parameters, encoding: .JSON)
.responseJSON { response in
print(response)
}
}
I am new to iOS
I would recommend you to use EVReflection for your JSON objects in Swift.
Just create an object for your JSON Object and then pass it to Alamofire with myJsonObject.toDictionary() as parameters.

IOS Swift Alamofire JSON Request

I am trying to make a JSON Request with Alamofire but the response is in Greek and Swift returns:
Response
{
id = 4;
name = "\U0395\U03bb\U03b1\U03b9\U03cc\U03bb\U03b1\U03b4\U03bf"
url = "http://www.gaiaskarpos.com/app/images/categories/olive.png";
}
The problem is at name field.
//Swift Alamofire Request
Alamofire.request(.GET, "http://gaiaskarpos.com/applegetCategores.php",
encoding:.JSON).validate().responseJSON{(response)->
Void in print("Response Json : \(response.result.value)")
I had a same issue in Arabic/Persian chars and It's my solution:
json variable :
{
message = "\U062f\U0633\U062a\U06af\U0627\U0647 \U0645\U0639\U062a\U0628\U0631 \U0646\U06cc\U0633\U062a";
status = 0;
}
So I casted json to [String: AnyObject] :
var test = json as? [String : AnyObject]
print(test)
It's fixed. You should give it a try.
Why is your encoding .JSON? You send .GET-request and you don't need to specify the type of encoding in your request.
Alamofire documentation say:
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
So use it. Links -> http://cocoadocs.org/docsets/Alamofire/1.1.3/ and https://github.com/Alamofire/Alamofire
You must specify the type of encoding when you pass parameters in the body of your request. It is for .POST and .PUT requests.
Try to print 'name' to Debug area. Maybe you'll get name in normal encoding... Xcode has the disadvantage: it shows not-UTF8 data in response like '\U0395\U03bb ... ... ... \U03b1\U03b9\' when there is some level of nested data in response.
Try to use NSUTF8StringEncoding with alamofire response
encoding: NSUTF8StringEncoding
Try to serialize the JSON with below code this might help you
let dict = NSJSONSerialization.JSONObjectWithData(jsonString.dataUsingEncoding(NSUTF8StringEncoding)!,
options: nil, error: nil) as [String : String]

Resources