Get the value of Error-Message in failure block of AFHTTPRequestOperation - ios

I need to get the value of Error-Message in the failure block of my request.
Here's the error:
Error Domain=com.alamofire.error.serialization.response Code=-1011
"Request failed: bad request (400)" UserInfo=0x165151b0
{NSErrorFailingURLKey=http://203.125.112.203:8090/megumi01/api/zipData?lastSynced=1441161682,
com.alamofire.serialization.response.error.response= { URL:
http://203.125.112.203:8090/megumi01/api/zipData?lastSynced=1441161682
} { status code: 400, headers {
"Access-Control-Allow-Headers" = "x-requested-with, Authorization, Content-Type, Accept";
"Access-Control-Allow-Methods" = "POST, GET, OPTIONS, DELETE, PUT";
"Access-Control-Allow-Origin" = "*";
"Access-Control-Max-Age" = 3600;
"Cache-Control" = "no-cache, no-store, max-age=0, must-revalidate";
Connection = close;
"Content-Type" = "application/json;charset=UTF-8";
Date = "Wed, 02 Sep 2015 10:38:57 GMT";
"Error-Code" = 0808;
"Error-Message" = "No updates available";
Expires = 0;
Pragma = "no-cache";
Server = "Apache-Coyote/1.1";
"Transfer-Encoding" = Identity;
"X-Application-Context" = "application:9090";
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = DENY;
"X-XSS-Protection" = "1; mode=block"; } }, NSLocalizedDescription=Request failed: bad request (400)}
I have tried putting "error" into NSData so I could convert it to NSDictionary but it becomes nil.
May I know how could I get the value of the custom header "Error-Message"?
TYIA!

below code may help you. try it.
NSLog(#"status code :%ld",(long)[operation.response statusCode]);
NSLog(#"Failure Response %#, %#", error, operation.response.description);

After thinking straightly, I was able to get the proper way to get the custom header in failure block of AFHTTPRequestOperation.
NSDictionary *userInfo = [error userInfo];
NSHTTPURLResponse *alamofireResponse = [userInfo objectForKey:#"com.alamofire.serialization.response.error.response"];
NSDictionary *allHeaders = [alamofireResponse allHeaderFields];
NSString *customMessage = [allHeaders objectForKey:#"Error-Message"];

Related

Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: forbidden (403)

I am using AFNetworking 3.1.0 to make a http request.
It shows below after i made the request. The code i made the request is in the bottom. The url below you can see is not visitable without ssl VPN.
Error Domain=com.alamofire.error.serialization.response Code=-1011
"Request failed: forbidden (403)"
UserInfo={com.alamofire.serialization.response.error.response= { URL:
https://223.71.215.70/web/1/http/0/10.100.5.105:6666/entry } { status
code: 403, headers {
Connection = "Keep-Alive";
"Content-Length" = 238;
"Content-Type" = "text/html; charset=iso-8859-1";
Date = "Wed, 14 Dec 2016 14:27:48 GMT";
"Keep-Alive" = "timeout=15, max=100";
"X-Frame-Options" = SAMEORIGIN; } }, NSErrorFailingURLKey=https://223.71.215.70/web/1/http/0/10.100.5.105:6666/entry,
NSLocalizedDescription=Request failed: forbidden (403),
com.alamofire.serialization.response.error.data=<3c21444f 43545950
45204854 4d4c2050 55424c49 4320222d 2f2f4945 54462f2f 44544420
48544d4c 20322e30 2f2f454e 223e0a3c 68746d6c 3e3c6865 61643e0a
3c746974 6c653e34 30332046 6f726269 6464656e 3c2f7469 746c653e
0a3c2f68 6561643e 3c626f64 793e0a3c 68313e46 6f726269 6464656e
3c2f6831 3e0a3c70 3e596f75 20646f6e 27742068 61766520 7065726d
69737369 6f6e2074 6f206163 63657373 202f7765 622f312f 68747470
2f302f31 302e3130 302e352e 3130353a 36363636 2f656e74 72790a6f
6e207468 69732073 65727665 722e3c2f 703e0a3c 2f626f64 793e3c2f
68746d6c 3e0a>} Request failed: forbidden (403)
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 30
let manager = AFHTTPSessionManager(sessionConfiguration: config)
manager.requestSerializer = AFHTTPRequestSerializer() // AFJSONRequestSerializer(writingOptions: .prettyPrinted)
manager.responseSerializer = AFHTTPResponseSerializer() // AFJSONResponseSerializer(readingOptions: .mutableContainers)
// manager.responseSerializer.acceptableContentTypes = ["text/html"]
manager.responseSerializer.acceptableContentTypes = ["application/json", "text/json", "text/JavaScript", "text/html", "text/plain"]
let policy = AFSecurityPolicy(pinningMode: .none)
policy.allowInvalidCertificates = true
policy.validatesDomainName = false
manager.securityPolicy = policy
manager.post(url, parameters: para, progress: nil, success: { (task:URLSessionDataTask, a:Any?) in
print(123)
}) { (task: URLSessionDataTask?, error: Error) in
// print(task?.description)
print(error)
print(error.localizedDescription)
}
I found that if my phone clock was out of sync...Maybe check that your phone is set to the right time "auto zone" and see if that works...
Reference URL: https://community.fitbit.com/t5/Charge-HR/Can-t-set-up-error-Forbidden-403/td-p/1053680

JSON Parsing getting Error NSErrorFailingURLKey in IOS

I am trying to print JSON response in first log.But whenever i try to get response from this URL and also from this URL .But whenever i make a request i am getting this error.
NSErrorFailingURLKey=http://wptrafficanalyzer.in/p/demo1/first.php/countries/, NSLocalizedDescription=Request failed: unacceptable content-type: text/html, com.alamofire.serialization.response.error.data
This is my Log File
2016-01-15 12:19:25.618 JSOnParsingWithActorList[3153:58905] Error: Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x78e25230> { URL: http://wptrafficanalyzer.in/p/demo1/first.php/countries/ } { status code: 200, headers {
"Cache-Control" = "max-age=3600";
Connection = "Keep-Alive";
"Content-Encoding" = gzip;
"Content-Length" = 490;
"Content-Type" = "text/html";
Date = "Fri, 15 Jan 2016 06:27:55 GMT";
Expires = "Fri, 15 Jan 2016 07:27:55 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.2.22 (Ubuntu)";
Vary = "Accept-Encoding";
"X-Powered-By" = "PHP/5.3.10-1ubuntu3.21";
} }, NSErrorFailingURLKey=http://wptrafficanalyzer.in/p/demo1/first.php/countries/, NSLocalizedDescription=Request failed: unacceptable content-type: text/html, com.alamofire.serialization.response.error.data=<7b22636f 756e7472 69657322 3a5b7b22 636f756e 7472796e 616d6522 3a22496e 64696122 2c22666c 6167223a 22687474 703a5c2f 5c2f7770 74726166 66696361 6e616c79 7a65722e 696e5c2f 705c2f64 656d6f31 5c2f696e 6469612e 706e6722 2c226c61 6e677561 6765223a 2248696e 6469222c 22636170 6974616c 223a224e 65772044 656c6869 222c2263 75727265 6e637922 3a7b2263 6f646522 3a22494e 52222c22 63757272 656e6379 6e616d65 223a2252 75706565 227d7d2c 7b22636f 756e7472 796e616d 65223a22 50616b69 7374616e 222c2266 6c616722 3a226874 74703a5c 2f5c2f77 70747261 66666963 616e616c 797a6572 2e696e5c 2f705c2f 64656d6f 315c2f70 616b6973 74616e2e 706e6722 2c226c61 6e677561 6765223a 22557264 75222c22 63617069 74616c22 3a224973 6c616d61 62616422 2c226375 7272656e 6379223a 7b22636f 6465223a 22504b52 222c2263 75727265 6e63796e 616d6522 3a225061 6b697374 616e6920 52757065 65227d7d 2c7b2263 6f756e74 72796e61 6d65223a 22537269 204c616e 6b61222c 22666c61 67223a22 68747470 3a5c2f5c 2f777074 72616666 6963616e 616c797a 65722e69 6e5c2f70 5c2f6465 6d6f315c 2f737269 6c616e6b 612e706e 67222c22 6c616e67 75616765 223a2253 696e6861 6c61222c 22636170 6974616c 223a2253 7269204a 61796177 61726465 6e617075 7261204b 6f747465 222c2263 75727265 6e637922 3a7b2263 6f646522 3a22534b 52222c22 63757272 656e6379 6e616d65 223a2253 7269204c 616e6b61 6e205275 70656522 7d7d2c7b 22636f75 6e747279 6e616d65 223a2243 68696e61 222c2266 6c616722 3a226874 74703a5c 2f5c2f77 70747261 66666963 616e616c
I am using AFNetworking for making URL call.I check this url's in Android.This URL content-type is Application/JSON but in IOS i am getting header content-type text/html.From this URL I am getting sucessful response from URL in JSON format.Please help for solve this issue.
This is my ViewController.m file
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://wptrafficanalyzer.in/p/demo1/first.php/countries/"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#",response);
}
}];
[dataTask resume];
}
Add this code:
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
After this :
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
It is well explained here : Upload an sqlite file
Your server page is returning text/html, but AFURLSessionManager is expecting JSON.
Edit:
As the above solution didn't work out , i found this link containing all possible solution for this error : Request failed: unacceptable content-type: text/html

Request failed: internal server error (500) and Cocoa error 3840, Invalid value around character 0 responses AFNetworking

It appears to be working in web:
Web Response Headers:
Connection:keep-alive
Content-Length:394
Content-Type:application/json
Date:Sun, 22 Mar 2015 18:36:06 GMT
Server:nginx/1.6.2
Vary:Accept-Encoding
X-Powered-By:Express
Web Request Headers:
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1NDVjYzNjYzQ2N2I3YjAyMDBhMWNkOWEiLCJpYXQiOjE0MjcwNDM3Mzk1NjQsImV4cCI6MTQ5MDExNTczOTU2NH0.Xqm-b12QWcEa6MPXyKa1E8m88hGZI9KfJl7Img3mACU
Connection:keep-alive
Content-Length:225
Content-Type:application/json;charset=UTF-8
Web Request Payload:
{"id":"550f15122cc2708c2d9c65b8","users":["xiruken#gmail.com"],"welcomeMessage":"Hi there. We’ll be using Next24 to keep track of our daily high priority items as a group during this project.","newUser":"xiruken#gmail.com"}
But not working in my native iOS project using objective-C...
Same parameters:
NSDictionary query:
{
id = 550f15122cc2708c2d9c65b8;
newUser = "xiruken#gmail.com";
users = (
"xiruken#gmail.com"
);
welcomeMessage = "Hi there. We will be using Next24 to keep track of our daily high priority items as a group during this project.";
}
AFNetworking code:
-(AFHTTPSessionManager *)sessionManager2{
if(!_sessionManager2){
_sessionManager2 = [[AFHTTPSessionManager alloc] initWithBaseURL: [NSURL URLWithString:API_URL]];
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
[_sessionManager2 setSecurityPolicy:securityPolicy];
_sessionManager2.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingAllowFragments];
NSArray *acceptedTypes = #[#"text/html", #"application/json", #"text/plain"];
_sessionManager2.responseSerializer.acceptableContentTypes = [NSSet setWithArray:acceptedTypes];
//add token
if([Helpers isLoggedIn]){
UserDM *user = [UserDM loadCustomObjectWithKey:DEFAULT_CURRENT_USER];
[self.sessionManager2.requestSerializer setValue:[NSString stringWithFormat:#"Bearer %#", user.accessToken] forHTTPHeaderField:#"Authorization"];
}
}
return _sessionManager2;
}
Using AFJSONResponseSerializer is giving me this error:
2015-03-23 03:28:26.773 Next25[5801:302572] Failed! Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x7fdbb252a6e0 {NSDebugDescription=Invalid value around character 0., NSUnderlyingError=0x7fdbb252c410 "Request failed: internal server error (500)"}
I even allowFragments and even set acceptableContentTypes
And changing it to AFHTTPResponseSerializer is giving me a different error:
2015-03-23 03:30:30.797 Next25[5852:303849] Failed! Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: internal server error (500)" UserInfo=0x7fb129e4e930 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7fb129e36320> { URL: https://myproject.com/api/projects/550f15122cc2708c2d9c65b8/invite_users } { status code: 500, headers {
Connection = "keep-alive";
"Content-Length" = 21;
"Content-Type" = "text/html";
Date = "Sun, 22 Mar 2015 19:26:56 GMT";
Server = "nginx/1.6.2";
Vary = "Accept-Encoding";
"X-Powered-By" = Express;
} }, NSErrorFailingURLKey=https://myproject.com/api/projects/550f15122cc2708c2d9c65b8/invite_users, com.alamofire.serialization.response.error.data=<496e7465 726e616c 20536572 76657220 4572726f 72>, NSLocalizedDescription=Request failed: internal server error (500)}

How to use PromiseKit to handle header-only response?

I'm using PromiseKit in an IOS app to communicate with a Rails RESTful backend,
and there're some calls that return only header, say by executing head 200 on the backend.
What I've tried is:
I used [NSURLConnection POST:url formURLEncodedParameters:parameters] to post data to backend, the backend did receive the data and responded with a head 200 message, but PromiseKit is reporting the following exception:
2014-07-31 11:19:39.501 HelloPOS[13223:60b] Error
Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be
completed. (Cocoa error 3840.)" (No value.) UserInfo=0xa4c5a90
{NSDebugDescription=No value., PMKURLErrorFailingDataKey={length = 1, capacity = 16, bytes = 0x20},
PMKURLErrorFailingURLResponseKey= { URL:
http://SOME_APP.SOME_HOST.com/api/v1/sales.json } { status code: 200,
headers {
"Cache-Control" = "max-age=0, private, must-revalidate";
Connection = "keep-alive";
"Content-Length" = 1;
"Content-Type" = "application/json";
Date = "Thu, 31 Jul 2014 03:19:25 GMT";
Etag = "\"7215ee9c7d9dc229d2921a40e899ec5f\"";
Server = "WEBrick/1.3.1 (Ruby/2.0.0/2014-05-08)";
Via = "1.1 vegur";
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-Request-Id" = "5a1c1aa1-4b42-41ea-8397-a5df8fa956bc";
"X-Runtime" = "0.013359";
"X-Xss-Protection" = "1; mode=block"; } }}
It's probably because header-only response has no body, and the error is caused
PS: I've changed the URL in the exception message
The problem is the server claims that the response has a JSON content of length 1 byte. But the response does not parse into JSON, so PromiseKit errors that promise.
PromiseKit doesn't provide a mechanism to ignore the response, but you could easily make your own promise here if you cannot fix the server to provide correct responses.
#import <OMGHTTPURLRQ.h>
- (PMKPromise *)myPromise:(id)args {
id rq = [OMGHTTPURLRQ POST:url:args];
id q = ;
return [PMKPromise new:^(PMKPromiseFulfiller fulfill, PMKPromiseRejecter reject){
[NSURLConnection sendAsynchronousRequest:rq queue:q completionHandler:^(id rsp, id data, NSError *urlError) {
if (urlError) {
reject(urlError)
} else {
fulfill(nil);
}
}];
}];
}
EDIT: PromiseKit now works around this specific situation, so you should no longer get this specific error.

NSURLConnection, NSURLAuthenticationChallenge failure response

When trying to log in to my app with iOS7 I'm getting a failure response with some description. This is NSLog of NSURLAuthenticationChallenge failureResponse:
<NSHTTPURLResponse: 0xa383570> { URL: <URL> } { status code: 401,headers {
"Content-Length" = 1385;"Content-Type" = "text/html;charset=utf-8";
Date = "Fri, 13 Jun 2014 12:14:24 GMT";
Server = "Apache-Coyote/1.1";
"Www-Authenticate" = "Basic realm=\"booo\"";
"x-errorCode" = 02;
"x-errorDescription" = "com.idealination.core.server.client.http.ServerException:
Request failed: <URL> Status: CLIENT_ERROR_UNAUTHORIZED
Error: #Unauthorized :: Invalid userid or password.";
} }
and I need that last line to know what error do I get. But when I use iOS6 and iPhone 3gs I get only:
<NSHTTPURLResponse: 0x1c507ae0>
What should I do to get a response like using iOS7? And why I'm getting a different response?
You should not be looking for the last line, you should be looking for the HTTP Status Code, in this case 401.
if(urlResponse.statusCode == 401) { }
If you need to convert that into what the status code means as a string use
NSString *status = [NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];

Resources