Get Response of XML HTTP url using alamofire and Swift4 IOS - ios

I am developing an application in which I need to get the response code of a HTTP URL, The URL returns an xml which is encrypted. I only need to get that encrypted response code into a variable.
I've used Alamofire for http request.
Thanks in advance!

Alamofire.request("URL Goes here",method:.get)
.response { response in
if let data = response.data {
print(data)
var xml = SWXMLHash.parse(data)
print(xml["e1"]["e2"].element?.text)
}
}

Related

Calling api giving same response even response data is changed

I am new to iOS and want to call an API for login. I am using Alamofire for HTTP request. I am getting a response from the server but I guess it is saving response in cache. So if I call api with different data is printing same response again. And one more question is I want to save session for later api call. How can I save session data and use it in header for later api call?
This is my Login API Call
let params = ["identity": txtId.text!, "pass": txtPassword.text!]
AF.request(LOGIN_URL, method: .post, parameters: params as Parameters).responseJSON { response in
print("response = \(response.result.value)")
}
One easy way to remove caches is to call this code before your network call:
URLCache.shared.removeAllCachedResponses()
Or you can also remove caches for a single request:
let urlRequest = URLRequest(url: URL(string: "https://...")!)
URLCache.shared.removeCachedResponse(for: urlRequest)
Then, make your network call:
let params = ["identity": txtId.text!, "pass": txtPassword.text!]
AF.request(LOGIN_URL, method: .post, parameters: params as Parameters).responseJSON { response in
print("response = \(response.result.value)")
}

Swift - Server response "unsupported_grant_type"

I'm trying to login using alamofire.
im using the following code:
let parameters = [
"username": "2gggggjggg",
"password": "2ubgh",
]
Alamofire.request(.POST, URL , parameters: parameters, encoding: .JSON).responseJSON { response in
print("request")
print(response.request) // original URL request
print("response")
print(response.response) // URL response
print("data")
print(response.data) // server data
print("result")
print(response.result) // result of response serialization
print("JSON")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
if let myData = response.data?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) {
SignUpVC.clientID = myData
print(myData)
}
}
the server response as follows:
data
Optional(<7b226572 726f7222 3a202275 6e737570 706f7274 65645f67 72616e74 5f747970 65227d>)
result
SUCCESS
JSON
JSON: {
error = "unsupported_grant_type";
}
what might the reason be? am i missing anything?
im new to implementing apps that connects to a server.
as far as i know the server uses Django with REST framework and oAuth2.
i hope to get enough help about it. I've tried to search a lot about this problem and how to resolve it but no luck.
thanks in advance.
Debugging check list
Did you use https in your url?
Did your server have Server Certificate from Certification authority Note iOS 9 will not connected to self sign
Certificate)?
Do you use object maper like "SwiftyJSON" object Model to json
not from the error massage I think you have to check your post url or you Server Certificate
let URL:String ="https://youURLHere"

How can I get data out of NSURLRequest config object

I have an Angular web build inside an iOS app and want to POST requests up to the native layer with some JSON that I can use to build some native functionality. I am using the old UIWebView (because Angular) so am using an NSURLProtocol to intercept the request. This works and I can break at the point that the request comes in. The problem is that I can not see the JSON in the data property at this point because it is not the response. The request is still in the config object but I have no idea how to grab this.
My angular code for creating the post is currently like this:
var newdata = $.param({
json: JSON.stringify({
name: "Lee"
})
});
$http.post(url, newdata)
and in my NSURLProtocol class I am successfully intercepting this POST in this method but the HTTPBody property is nil:
override class func canInitWithRequest(request:NSURLRequest) -> Bool {
if (request.URL!.absoluteString as NSString).containsString("request_media_gallery") {
if(request.HTTPBody != nil){
let data:NSData = request.HTTPBody!
print(data)
}
return true
}
return request.URL?.host == "file"
}
If I debug this in chrome I get a 405 because of CORS but I can see that my request object does not have any data but does have a config object. Here's the console log from Chrome:
By the time a URL request gets down to the protocol layer, IIRC, the URL Loading System sanitizes it in a lot of ways. In particular, if a request has an HTTPBody object associated with it, it basically does this:
req.HTTPBodyStream = [NSInputStream inputStreamWithData:req.HTTPBody];
req.HTTPBody = nil;
As a result, to get the data, you need to read from the HTTPBodyStream, regardless of whether the request was originally created with an NSData object or a body stream.

Alamofire Get Request and JSON Response

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.

Handle a JSON Response with Alamofire in Swift

I have a problem I want to handle a JSON Response with Alamofire in Swift
So I found this answer on Stackoverflow unfortunately this post is a few days older.
My question is how can I receive the data from Alamofire on first button press (without swiftyJSON).
I hope someone could help me.
This is the link I found on Stackoverflow.
Handle JSON Response with Alamofire in Swift
this is a small example.
This is what the JSON returns if it fails json_file.json
{ "transaction":"error" }
This is what the JSON returns if its success json_file.json
{ "transaction":"success" }
this is the code , you must add your own URL that will return any of those json responses. (example only)
Alamofire.request(.GET, "http://myjsonexamplewebsite.com/json_file.json", parameters:nil)
.responseJSON { (_, _, JSON, _) in
//println(JSON)
var response = JSON as NSDictionary
var transaction = response.objectForKey("transaction") as String
if transaction == "success" {
NSLog("JSON response was successfull")
}
else {
NSLog("JSON response had an Error")
}
}

Resources