Alamofire Get Request and JSON Response - ios

I'm trying to use the Yoda API and send a request using the Alamofire Swift framework. I know that the API is correctly working, as I have tested the endpoint with my Mashape API key multiple times. I can also see that the requests are being sent (homepage of Mashape under my application). However my JSON response is always nil.
func handleRequest(words:String){
var saying = words.stringByReplacingOccurrencesOfString(" ", withString: "+");
saying = "?sentence=" + saying;
let url = NSURL(string: (baseURL+saying));
println(url);
var response:String;
Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = additionalHeaders;
Alamofire.request(.GET, url!).responseJSON { (_, _, JSON, _) in
println(JSON);
}
}
The words string can be "This is my first sentence" and it will automatically replace the spaces with "+" as per the API spec. Please Ignore the multiple println statements, they are just for debugging.
This is just proof of concept code, its purposely not doing much error checking and isn't pretty for that reason. If you have any suggestions I would appreciate them.

For some reason it's an issue I've too with the Alamofire request for JSON. It is the way I handle the JSON requests using Alamofire :
Alamofire.request(.GET, urlTo, parameters: nil, encoding: .URL).responseString(completionHandler: {
(request: NSURLRequest, response: NSHTTPURLResponse?, responseBody: String?, error: NSError?) -> Void in
// Convert the response to NSData to handle with SwiftyJSON
if let data = (responseBody as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
let json = JSON(data: data)
println(json)
}
})
I strongly recommend you using SwiftyJSON to manage the JSON in a better and easy way, it's up to you.
I hope this help you.

Alamofire request have several method for handle response. Try to handle data response and convert it to String. Confirm that response JSON is normal.
Alamofire.request(.GET, url!).response { (_, _, data, error) in
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
println(str)
println(error)
}
Also checkout error while parsing JSON data.

Related

Could not cast NSDicationry with NSData in WebService call request

Trying to wrap Codable response data from WebService
used cocoa pod
pod 'WebService', '~> 0.4'
var webServiceObject : WebService = WebService()
webServiceObject.sendRequest(URLString, parameters: parameters as NSDictionary?, requestType: .post, success: {response,data in
do{
// Handle data when request Success
let jsonDecoder = JSONDecoder()
do {
let result = try jsonDecoder.decode([ResponseModelValue].self, from: data as! Data)
print(response?.statusCode as Any)
print("Success Response Value", result)
}
} catch {
print(error)
}
}, failed: {
(response : HTTPURLResponse?, ResponseDict : Any?) in
print(response?.statusCode as Any)
print("Failed Response Dictionary", ResponseDict!)
// Handle data when request fails
}, encoded: false )
I got following error
Could not cast value of type '__NSDictionaryI' (0x10c81ab38) to 'NSData' (0x10c819620).
Can any one suggest me what I done wrong here, so I can parse proper response data with codable [ResponseModelValue]
After looking at that library, it appears that it will turn the response into a dictionary if possible and fall back to returning data.
https://github.com/kansaraprateek/WebService/blob/master/WebService/Classes/WebService.swift#L281
It doesn't appear like there is a way to configure that behaviour. The library was also created before Codable was created. You may need to reach out the library owner for a fix, fork the repo and fix it yourself, or switch to using URLSession since the code you posted is mostly the same as a URLSession call.

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

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.

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]

handle JSON response with SwiftyJSON

I tried a long time to handle a JSON response with SwiftyJSON, but I don't know how to parse the response. Here's my code:
var jsonString:String = ""
Alamofire
.request(.GET, url + "/HMServer/rest/administration/version")
.responseJSON {
(request, response, data, error) -> Void in
let json = JSON(object: data!)
//here I want to do something with parsing
}
The requests I do with Alamofire and get back a JSON response. The response look like:
[message: [SERVER_VERSION: 0.1, INTERFACE_VERSION: 0.1], type: success]
I want to save all elements in strings and give them back. How can I parse the JSON response saved in the let let json? I tried to use Alamofire-SwiftJSON but the code does not work. All examples I found are too old because the SwiftyJSON code was refactored a few days ago.
THX!
I have fixed Alamofire-SwiftJSON's issue,
but you can do it by yourself in responseJSON's closure like:
Alamofire.request(.GET, url + "/HMServer/rest/administration/version")
.responseJSON { (request, response, data, error) -> Void in
if error != nil {
self.swiftyJSON = SwiftyJSON.JSON.Null(error)
} else if object != nil {
self.swiftyJSON = SwiftyJSON.JSON(object: object!)
} else {
self.swiftyJSON = SwiftyJSON.JSON.Null(nil)
}
}
Above code is not like Alamofire-SwiftJSON in the global queue, the initialization (AnyObject to SwiftyJSON) is running in the main queue.

Resources