Problems with JSON and Alamofire request - ios

I am trying to send a request with the next code:
func getLogin(user: String, password: String) {
let url = URL(string: "https://www.url.es/api/login")!
let parameters: Parameters = [
"usuario" : "\(user)",
"clave" : "\(password)"]
let headers: HTTPHeaders = [
"Authorization": "Basic TOKEN"
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate()
.responseJSON { response in
print("repuesta")
print(response.request as Any) // original URL request
print(response.response as Any) // URL response
print(response.result.value as Any) // result of response serialization
debugPrint(response)
}
}
But I am getting this response:
[Request]: https://www.url.es/api/login
[Response]: <NSHTTPURLResponse: 0x608000220b40> { URL: https://www.url.es/api/login } { status code: 401, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 28;
"Content-Type" = "text/plain; charset=utf-8";
Date = "Mon, 16 Jan 2017 20:44:14 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/8.5";
"Www-Authenticate" = Bearer;
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} }
[Data]: 28 bytes
[Result]: FAILURE: responseValidationFailed(Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(401))
[Timeline]: Timeline: { "Request Start Time": 506292395.911, "Initial Response Time": 506292396.351, "Request Completed Time": 506292396.352, "Serialization Completed Time": 506292396.353, "Latency": 0.440 secs, "Request Duration": 0.441 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.441 secs }
I am sending the request with paw http client and the response is ok.
I am working with swift3, alamofire 4 and iOS10

According to the response you have there it looks like your username and password is incorrect. Try printing the parameters dictionary to make sure it is correct. Something that can happen sometimes is if you forget to unwrap an optional value it will still get sent. For example
let optionalString:String? = "blablabla"
print(optionalString) //prints: Optional(blablabla)
Edit:
Another thing I noticed is you set the encoding to JSON but the header Content Type is PlainText. Try setting the encoding to URLEncoding.default and make sure the headers are set appropriately for what the server is expecting.

Related

Sending page no in URL request issue. Getting success but empty result

My Api is having Constants.getliked = "get-liked-story?page=1" at it's tail. I am requesting via alamofire but not getting the response. How can I send page number which includes ? and = sign.
let url : String = Constants.wevlrBaseUrl + Constants.privateLink + Constants.getliked
//let sv = UIViewController.displaySpinner(onView: view)
let userToken = UserDefaultValues.authToken
let headers: HTTPHeaders = ["Authorization": "Bearer " + userToken!]
let parameters: Parameters = [
"page": "1" ]
Alamofire.request(url, method: .get, parameters: parameters,headers:headers).responseJSON { response in
print("request-",response.request!)
print("response-",response.response!)
print("data-",response.data!)
print("result-",response.result)
debugPrint(response)
if let JSON = response.result.value {
print("json: \(JSON)")
}
}
output:
[Request]: GET http://169.65.125.111/abcd/public/api/v1/get-liked-story?page=1
[Response]: { URL: http://169.65.125.111/abcd/public/api/v1/get-liked-story?page=1 }
{
Status Code: 200, Headers
{
"Cache-Control" = (
"no-store, no-cache, must-revalidate"
);
Connection = (
"Keep-Alive"
);
"Content-Length" = (
2
);
"Content-Type" = (
"application/json"
);
Date = (
"Mon, 07 Oct 2019 11:37:43 GMT"
);
Expires = (
"Thu, 19 Nov 1981 08:52:00 GMT"
);
"Keep-Alive" = (
"timeout=5, max=99"
);
Pragma = (
"no-cache"
);
Server = (
"Apache/2.4.18 (Ubuntu)"
);
} }
[Data]: 2 bytes
[Result]: SUCCESS: (
)
[Timeline]: Timeline: { "Request Start Time": 592141063.093, "Initial Response Time": 592141063.178, "Request Completed Time": 592141063.178, "Serialization Completed Time": 592141063.178, "Latency": 0.086 secs, "Request Duration": 0.086 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.086 secs }
json: (
)
Suppose this value for the variables in Constants
let wevlrBaseUrl = "https://stackoverflow.com"
let privateLink = "/questions"
let getliked = "/get-liked-story?page=1"
then use Alamofire request method with url and headers parameters only

Get Response using Alamofire

I am using Alamofire to make Get Response but unable to get the Valid Response . I am using below details . I dono where i am making mistake.
let myID = MEGHA-WORK SE-107
let headers = ["Authorization": "Basic \(base64Credentials)" , "ID": (myID).trimmingCharacters(in: .whitespaces) ]
let parameters:Parameters = ["ID": (myID).trimmingCharacters(in: .whitespaces)]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 60
manager.request(url, method: .get, parameters: parameters, encoding: URLEncoding.queryString , headers: headers).responseJSON { (response) in
debugPrint(response)
if response.response?.statusCode == 200 || response.response?.statusCode == 201 {
if let value = response.result.value {
let json = JSON(value)
print(json)
completion(json, nil)
}
}
Task <343CF648-7C9A-4E03-9A82-A88BC41EA926>.<6> finished with error - code: -1005
Response
[Request]: GET https://my-services.myservices.com:443/prweb/api/v1/cases?ID=MEGHA-WORK%20SE-107
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x109ce9500 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x10d53db00 [0x1b271c310]>{length = 16, capacity = 16, bytes = 0x100201bba06d196d0000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://my-services.myservices.com:443/prweb/api/v1/cases?ID=MEGHA-WORK%20SE-107, NSErrorFailingURLKey=https://my-services.myservices.com:443/prweb/api/v1/cases?ID=MEGHA-WORK%20SE-107, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.}
[Timeline]: Timeline: { "Request Start Time": 553592494.567, "Initial Response Time": 553592497.615, "Request Completed Time": 553592497.615, "Serialization Completed Time": 553592497.616, "Latency": 3.049 secs, "Request Duration": 3.049 secs, "Serialization Duration": 0.000 secs, "Total Duration": 3.049 secs }
It seems that the reason is already printed there:
Code=-1005 "The network connection was lost."
Restarting the simulator and erasing all content and settings seems to fix this for others (Simulator->Hardware->Erase All Content and Settings...)
Please check this thread.
You can handle this way :
if (responseJson.response?.statusCode)! > 200 && (responseJson.response?.statusCode)! < 300{
// handle as appropriate because the response will be success
} else {
}
It may helps you to handle the crash. Thank you

How to detect 304 statusCode with Alamofire

Is there a way to detect 304 Not Modified response with Alamofire 4? I find that Alamofire response.statusCode is always 200 even if server responded with 304.
Network call setup:
Alamofire
.request("http://domain.com/api/path", method: .get)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseJSON { response in
print(response.response?.statusCode)
}
Alamofire response header
<NSHTTPURLResponse: 0x61800003e1c0> { URL: http://domain.com/api/path } { status code: 200, headers {
"Access-Control-Allow-Headers" = "content-type, authorization";
"Access-Control-Allow-Methods" = "GET, PUT, POST, DELETE, HEAD, OPTIONS";
"Access-Control-Allow-Origin" = "*";
"Cache-Control" = "private, must-revalidate";
Connection = "keep-alive";
"Content-Type" = "application/json";
Date = "Mon, 23 Jan 2017 23:35:00 GMT";
Etag = "\"f641...cbb6\"";
"Proxy-Connection" = "Keep-alive";
Server = "nginx/1.10.1";
"Transfer-Encoding" = Identity;
} }
Server response
HTTP/1.1 304 Not Modified
Server: nginx/1.10.1
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: content-type, authorization
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Cache-Control: private, must-revalidate
ETag: "f641...cbb6"
Date: Mon, 23 Jan 2017 23:35:00 GMT
Since NSURLSessions default behavior is to abstract from cached 304 responses by always returning 200 responses (but not actually reloading the data), I first had to change the cachingPolicy as follows:
urlRequest.cachePolicy = .reloadIgnoringCacheData
Then, I adjusted the status codes of the validate function to accept 3xx responses and handled the codes accordingly:
Alamofire.request("https://httpbin.org/get")
.validate(statusCode: 200..<400)
.responseData { response in
switch response.response?.statusCode {
case 304?:
print("304 Not Modified")
default:
switch response.result {
case .success:
print("200 Success")
case .failure:
print ("Error")
}
}
}
You can use manual response validation with Alamofire as outlined here.
Alamofire.request("https://httpbin.org/get")
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseData { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}

Handle non-JSON response from POST request with Alamofire

I'm using Alamofire 3 and the end point I'm calling (I don't own the server) accepts a POST request and returns HTML as a response.
I am able to get the HTML response when using curl in the command line, however Alamofire doesn't return the response body, but only the header.
This is my code:
let headers = [
"Referer": "SOMEURL"
]
Alamofire.request(.POST, url, headers: headers)
.validate()
.response { request, response, data, error in
// do something with response
}
response is:
Optional(<NSHTTPURLResponse: 0x7f9ba3759760> { URL: SOMEURL } { status code: 200, headers {
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Type" = "text/html";
Date = "Thu, 22 Sep 2016 15:19:20 GMT";
Server = nginx;
"Transfer-Encoding" = Identity;
Vary = "Accept-Encoding";
} })
and data is:
Optional<NSData>
- Some : <>
Any thoughts?

Twitter API in SWIFT via Alamofire

I currently try to send a simple query - in Postman it works fine for me, but in SWIFT I simply cant get it working
My Code looks like:
func TWITTER_getPosts(username:String){
let headers = [
"screen_name": "username",
"authorization": "OAuth oauth_consumer_key=\"<KEY>\",oauth_token=\"<KEY>\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1469246792\",oauth_nonce=\"n6Sxbq\",oauth_version=\"1.0\",oauth_signature=\"<KEY>\"",
"include_rts": "false"
]
Alamofire.request(.GET, "https://api.twitter.com/1.1/statuses/user_timeline.json", parameters: headers)
.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)")
}
}
}
I Always end in a
errors = (
{
code = 215;
message = "Bad Authentication data.";
One of the parameters for the request method is incorrect.
If you are passing headers, they shouldn't be passed in parameters, they should be passed as the following:
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
.responseJSON { response in
debugPrint(response)
}
headers: headers should be the way to go.

Resources