Alamofire4 jsonSerializationFailed in response - ios

I use Alamofire4 and I have a jsonSerializationFailed error in responseJson.
It seems that the response is not well formatted Json :
AlmF Failure Reason: jsonSerializationFailed(Error Domain=NSCocoaErrorDomain
Code=3840 "Invalid value around character 0." UserInfo=
{NSDebugDescription=Invalid value around character 0.})
AlmF Underlying error: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})
Here is the code displaying there error:
case .responseSerializationFailed(let reason):
print("AlmF Response serialization failed: \(error.localizedDescription)")
print("AlmF Failure Reason: \(reason)")
}
Here is the result of debugPrint(response) for
.responseJSON { response in:
=>
[Request]: http://myserver.com/Images.zip
[Response]: <NSHTTPURLResponse: 0x60000003cde0> { URL: http://myserver.com.com/Images.zip } { status code: 200, headers {
"Accept-Ranges" = bytes;
Connection = close;
"Content-Length" = 117127;
"Content-Type" = "application/zip";
Date = "Tue, 01 Nov 2016 21:28:23 GMT";
Etag = "\"701a02b-1c987-534eb9a863980\"";
"Last-Modified" = "Fri, 10 Jun 2016 12:23:18 GMT";
Server = Apache;
"X-Powered-By" = PleskLin;
Where should I format the Json, I thought Alamofire do that
Edit :
Before my code with Swift2 was:
.response { _, _, _, error in
if let error = error {
SpeedLog.print("DownloadVC Failed with error: \(error)")
} else {
SpeedLog.print("DownloadVC zip downloaded")
}

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

Create Node Error

UPDATE: Make sure to set up frameworks correctly SOLVED PROBLEM
I am trying to create a node to my Neo4j database from IOS.
Here is my code after the initial connection.
func createNode() {
let node = Node()
let randomString: String = NSUUID().UUIDString
node.setProp("name", propertyValue: "Matt Winfrey" + randomString)
node.setProp("born", propertyValue: "1991" + randomString)
node.addLabel("Person")
theo.createNode(node, completionBlock: {(node, error) in
println("new node \(node,error)")
});
}
I am getting a 500 error
new node (nil, Optional(Error Domain=com.theo.network.error Code=-1 "The operation couldn’t be completed. (com.theo.network.error error -1.)" UserInfo=0x7ff2b1fa9290
{ status code: 500, headers {
"Cache-Control" = "must-revalidate,no-cache,no-store";
Connection = "keep-alive";
"Content-Length" = 0;
"Content-Type" = "text/html; charset=ISO-8859-1";
Date = "Tue, 19 May 2015 19:44:42 GMT";
Server = "nginx/1.7.6";
} }, TheoResponseCode=500, NSLocalizedDescriptionKey=There was an error processing the request}))
Any help would be great.

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