I already searched everywhere and this issue that should have been trivial is taking longer than I wanted therefore I am reaching you for help.
I am using swift and integrated restkit using cocoapods.
Despite, as you can see the screenshots/log, the header is fine however the outgoing http packet is not consistent.
AppDelegate:
RKlcl_configure_by_name("RestKit/Network", RKlcl_vTrace.value);
RKlcl_configure_by_name("RestKit/ObjectMapping", RKlcl_vTrace.value);
ObjectManagerCode:
let objectManager: RKObjectManager = RKObjectManager(baseURL: NSURL(string: Endpoints.BaseUrl.toString()))
objectManager.requestSerializationMIMEType = RKMIMETypeJSON;
let username = "TestUser"
let password = "password"
objectManager.HTTPClient.setAuthorizationHeaderWithUsername(username, password: password)
objectManager.HTTPClient.setDefaultHeader("whatIWantForChristmas", value: "You")
objectManager.HTTPClient.allowsInvalidSSLCertificate = true
Request:
var requestUrl = cds.objectManager!.requestWithObject(
nil,
method: RKRequestMethod.GET,
path: endpoint.path,
parameters: endpoint.parameters())
cds.objectManager!.getObjectsAtPath(
endpoint.path,
parameters: endpoint.parameters(),
success:
{
(RKObjectRequestOperation, RKMappingResult) -> Void in
println(RKObjectRequestOperation.description)
Logger.Info("Success");
},
failure: {
(RKObjectRequestOperation, error) -> Void in
Logger.Error("Error: \(error.description)")
println(RKObjectRequestOperation.HTTPRequestOperation.description)
})
Log:
T restkit.network:RKObjectRequestOperation.m:178 GET 'http://website/api?format=json':
request.headers={
Accept = "application/json";
"Accept-Language" = "en;q=1, fr;q=0.9, de;q=0.8, zh-Hans;q=0.7, zh-Hant;q=0.6, ja;q=0.5";
Authorization = "Basic VGVzdFVzZXI6cGFzc3dvcmQ=";
"User-Agent" = "malaria-ios/1 (iPhone Simulator; iOS 8.3; Scale/2.00)";
whatIWantForChristmas = You;
}
...
E restkit.network:RKObjectRequestOperation.m:576 Object request
failed:Underlying HTTP request operation failed with error:
Error Domain=org.restkit.RestKit.ErrorDomain Code=-1011 "Expected status code in (200), got 403"
UserInfo=0x7ff54ae4f690 {NSLocalizedRecoverySuggestion={"detail":"Authentication credentials were not provided."}
What I figured out:
I can send anything in the header as long as it isn't "Authorization", if I change to "Authorization2", ok. The header "WhatIWantForChristmas" is also there. The authorization isn't despite being present in the log! It seems that the underlying software filters.
Out of paranoia I tried turning off firewall, cleaning project, reseting iOS simulator and nada. The application I used to see the HTTP packets is Charles.
What am I doing wrong?
Url for the screenshot pf Charles: http://s7.postimg.org/pfwn7kyq2/Screen_Shot_2015_06_20_at_21.jpg
Related
I have standard code in Swift like below:
private func testFormUrlEncodedRequest() {
let headers = [
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
]
let postData = NSMutableData(data: "user_id=5874ae8ae9a98c2d6cef1da8".data(using: String.Encoding.utf8)!)
postData.append("&offset=0".data(using: String.Encoding.utf8)!)
postData.append("&limit=20".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "http://www.example.com/endpoint")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
ViewController.log(request: request as! URLRequest)
print((request as URLRequest).curlString)
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
ViewController.log(data: data, response: response as? HTTPURLResponse, error: error)
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
}
But the problem is that it hangs on, and then request times out with error.
REST API is written in Node.js and gets error in body-parser module like request aborted.
I can make successfully the same request with POSTMAN or curl (from Terminal) and I get correct response.
Code on server which I have no access to seems to be also rather standard, and was used in previous projects where it was tested to work correctly with iOS apps.
I have no idea why this request goes ok with POSTMAN and doesn't work with URLSession in Swift.
Any help will be beneficial.
Here is error message printed to console I am getting:
Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x6000013196e0
{Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}},
NSErrorFailingURLStringKey=http://example.com/api/endpoint, NSErrorFailingURLKey=http://example.com/api/endpoint,
_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.})
This request gives error in such cases:
1. form-url-encoded params in HTTP request body
2. raw application/json params in HTTP request body
3. It works if params are passed in query params
4. It crashes with request aborted error on server side (body-parser module)
5. node.js uses standard app.use()
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
It uses http without SSL but in Info.plist there is App Transport Security > Allow Arbitrary Loads set to YES etc.
UPDATE:
This is error on server side
BadRequestError: request aborted
at IncomingMessage.onAborted (/Users/michzio/Click5Interactive/Reusable Parts/NetworkApi/node_modules/raw-body/index.js:231:10)
at emitNone (events.js:86:13)
at IncomingMessage.emit (events.js:188:7)
at abortIncoming (_http_server.js:381:9)
at socketOnClose (_http_server.js:375:3)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at TCP.Socket._destroy.cb._handle.close [as _onclose] (net.js:510:12)
Node.js Test Code:
const express = require('express');
const port = 9001;
const app = express();
const bodyParser = require('body-parser');
var todos = [{id:1, title:'buy the milk'}, {id:2, title:'rent a car'}, {id:3, title:'feed the cat'}];
var count = todos.length;
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json());
app.get('/test', (request, response) => {
console.log("-----")
console.log(request.params);
console.log(request.body);
console.log(request.query);
console.log("-----")
response.status(200).json( todos );
});
app.listen(port);
It seems that GET + query params works, and POST + body params (url-from-encoded or application/json) also works correctly.
So it doesn't work for GET body params url-form encoded and GET body params application/json. Is it some limitation of URLSession/URLRequest in Swift. POSTMAN can pass params in body with GET and server receives it in request.body !
UPDATE 2!
Yes, it seems that in Android/Kotlin with OkHttpClient there even is not possible to define Request Body with GET method. And there is also this error. Maybe this only works with POSTMAN and curl, and should not be used in real application scenario to join GET and body params.
public fun makeNetworkRequest(v: View) {
object : Thread() {
override fun run() {
val client = OkHttpClient()
val mediaType = MediaType.parse("application/json")
val body = RequestBody.create(mediaType, "{ \"test\" : \"nowy\", \"test2\" : \"lol\" }")
/*
val request = Request.Builder()
.url("http://10.0.2.2:9001/test")
.get()
.addHeader("Content-Type", "application/json")
.build()
*/
val mySearchUrl = HttpUrl.Builder()
.scheme("http")
.host("10.0.2.2")
.port(9001)
.addPathSegment("test")
.addQueryParameter("q", "polar bears")
.build()
val request = Request.Builder()
.url(mySearchUrl)
.addHeader("Accept", "application/json")
.method("GET", body)
.build()
val response = client.newCall(request).execute()
Log.d("RESPONSE", response.toString())
}
}.start()
}
I am a .net developer but very new to iOS and swift development, just need help with consuming Web API using Swift2
The Asp.net Web API has been built with OAuth2 authentication, published to my Azure VM server with SSL certificate installed. The API site itself works properly, tested through Postman
However I got stuck when started writing first few lines of code in Swift trying to get Authentication token. After reading some online tutorials I decided to engage Alamofire, and produced below codes snippet:
func GetToken() {
let params = [
"grant_type" : "password",
"username" : "123456#qq.com",
"password" : "averygoodpassword"
]
let headers = [
"Content-Type" : "application/x-www-form-urlencoded"
]
request(.POST, "https://api.example.com/token",
parameters: params,
headers: headers,
encoding: .JSON)
.responseJSON { request, response, result in
print (request)
print (response?.description)
print (result)
switch result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
case .Failure(let data, let error):
print("Request failed with error: \(error)")
if let data = data {
print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
}
}
}
}
It ends up with below output in Xcode which didn't seem to be OK. The error = unsupported_grant_type told me that the request were sent to server but the parameters were not sent with request properly. I really cannot figure out the reason and solution, had been digging on Internet for a few days but still feeling desperate with it. Can anyone help please? Even if someone can provide a pure swift solution without any 3rd party library will be greatly helpful. Thanks!
Xcode output:
Optional( { URL: https://api.example.com/token })
Optional(" { URL: https://api.example.com/token } { status code: 400, headers {\n \"Access-Control-Allow-Headers\" = \"Content-Type\";\n \"Access-Control-Allow-Methods\" = \"GET, POST, PUT, DELETE, OPTIONS\";\n \"Access-Control-Allow-Origin\" = \"*\";\n \"Cache-Control\" = \"no-cache\";\n \"Content-Length\" = 34;\n \"Content-Type\" = \"application/json;charset=UTF-8\";\n Date = \"Fri, 30 Sep 2016 10:30:31 GMT\";\n Expires = \"-1\";\n Pragma = \"no-cache\";\n Server = \"Microsoft-IIS/8.5\";\n \"X-Powered-By\" = \"ASP.NET\";\n} }")
SUCCESS
Success with JSON: {
error = "unsupported_grant_type";
}
I had a similar problem trying to POST to MailGun for some automated emails I was implementing in an app.
I was able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.
// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
keys = NSDictionary(contentsOfFile: path)
}
if let dict = keys {
// variablize our https path with API key, recipient and message text
let mailgunAPIPath = dict["mailgunAPIPath"] as? String
let emailRecipient = "bar#foo.com"
let emailMessage = "Testing%20email%20sender%20variables"
// Create a session and fill it with our request
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler#<my domain>.com%3E&to=reservations#<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)
// POST and report back with any errors and response codes
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:
https://API:key-<my key>#api.mailgun.net/v3/<my domain>.com/messages?
I'm slightly opposed to using 3rd party libraries, especially for small things like a http POST and this seems like a much more maintainable solution to me. Anyways, hope this helps, let me know if you have any questions!
I'm working on a iOS project in Swift 2.0, which has Web service calls, these services are slow to respond and that is normal, can be up to 1 minute or a little more, when i call the service 70% of the time it answers with the error "the network connection was lost." The tests were conducted in both simulator and different phone devices and iPad and the result is the same. The network connection is strong and the same application was also created on Android and working properly almost 100% of the time.
The way I call services from any view is as follows:
#IBAction func contratarAct(sender: AnyObject) {
conexion.delegate = self
loadingView = MEXLoadingView(delegate: self, title: "Espere por favor", percent: false, view: self.view)
self.loadingView.showAnimated(true)
let url = urlServicios.urlBaseServicios + "/" + idSolicitud + "/" + idNoCliente + "/CONTRATO"
conexion.consultaServicioGET(url, httpMethod: "PUT")
}
And the method that is executed is as follows:
func consultaServicioGET(url : String, httpMethod : String ){
let urlString = url
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.timeoutInterval = 540
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
var session = NSURLSession.sharedSession()
request.HTTPMethod = httpMethod
let urlconfig = NSURLSessionConfiguration.defaultSessionConfiguration()
urlconfig.timeoutIntervalForRequest = 540
urlconfig.timeoutIntervalForResource = 540
session = NSURLSession(configuration: urlconfig, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithRequest(request , completionHandler: {
(data:NSData?, response:NSURLResponse?, error:NSError?) in
if error != nil {
let jsonError : NSDictionary = NSDictionary()
self.delegate?.respuestaServicioGET!(jsonError, mensaje: "\(error!.localizedDescription)")
return
}
let jsonString = NSString(data: data!,encoding: NSASCIIStringEncoding)
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
let json: NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if (json.isKindOfClass(NSDictionary) ){
self.delegate?.respuestaServicioGET!(json, mensaje: "OK")
}else{
let jsonError : NSDictionary = NSDictionary()
self.delegate?.respuestaServicioGET!(jsonError, mensaje: "ERROR")
}
})
task.resume()
}
the error displayed is:
error=Optional(Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x7fbde5f51df0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={_kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://particulares-gw-obparticularesmx-pre.appls.cto2.paas.gsnetcloud.com:443/OPB/57dadf7de4b0ac2e518de44a/57dadf7de4b06c6b04ef0dcf/CONTRATO, NSErrorFailingURLKey=https://particulares-gw-obparticularesmx-pre.appls.cto2.paas.gsnetcloud.com:443/OPB/57dadf7de4b0ac2e518de44a/57dadf7de4b06c6b04ef0dcf/CONTRATO, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.})
I add some code like the following:
urlconfig.timeoutIntervalForRequest = 540
urlconfig.timeoutIntervalForResource = 540
Trying to get more "timeout" but this is not looks like a timeout.
I can not get out of this error for days, any help will be greatly appreciated. I'm desperate.
If you're expecting a socket to stay open for minutes at a time, you're in for a world of hurt. That might work on Wi-Fi, but on cellular, there's a high probability of the connection glitching because of tower switching or some other random event outside your control. When that happens, the connection drops, and there's really nothing your app can do about it.
This really needs to be fixed by changing the way the client requests data so that the responses can be more asynchronous. Specifically:
Make your request.
On the server side, immediately provide the client with a unique identifier for that request and close the connection.
Next, on the client side, periodically ask the server for its status.
If the connection times out, ask again.
If the server says that the results are not ready, wait a few seconds and ask again.
On the server side, when processing is completed, store the results along with the identifier in a persistent fashion (e.g. in a file or database)
When the client requests the results for that identifier, return the results if they are ready, or return a "not ready" error of some sort.
Have a periodic cron job or similar on the server side to clean up old data that has not yet been collected.
With that model, it doesn't matter if the connection to the server closes, because a subsequent request will get the data successfully.
I faced the same issue and I am attaching a screenshot of the resolution to show how I resolved the issue.
In my case, the issue was that the API requests are blocked from the server Sucuri/Cloudproxy (Or you can say firewall service). Disabling the firewall resolved the issue
I don't why but it's works when I add sleep before my request:
sleep(10000)
AF.request(ViewController.URL_SYSTEM+"/rest,get_profile", method: .post, parameters: params, encoding: JSONEncoding.default , headers: headers).responseJSON { (response) in
}
I faced this issue and spend more than 1 week to fix this. AND i just solved this issue by changing Wifi connection.
I'm working on a school project, which is developing a Web application with an API and an iPhone app with swift. I developed the website in Laravel with Homestead/Vagrant.
But when it comes to the iPhone app, i'm facing with a problem:
When a user presses the login button the app sends a http POST request to the API and the API checks if the users exists in the db, if so then it will return a token, after which the user will be redirected to the dashboard. This works fine on the xcode simulator.
My code of the request part looks like this:
var loginUrl = "http://10.1.1.33/api/login" + "?email=" + self.email + "&password=" + self.password
let request = NSMutableURLRequest(URL: NSURL(string: loginUrl)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request, completionHandler: {
data, response, error -> Void in
guard error == nil else {
print("First Error!!! \(error)")
self.errorLabel.text = "Request timed Out"
self.enableLoginBtn(true, buttonText: "Login")
return
}
do {
let data: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
// Okay, the `json` is here, let's get the value for 'success' out of it
let json = JSON(data!)
dispatch_async(dispatch_get_main_queue(), {
if json["token"] != nil {
print("Login successvol!)")
if self.saveSession(json["token"].string!) {
self.enableLoginBtn(true, buttonText: "Login")
self.goToDashboard()
}else {
print("Saving token went wrong")
}
}else {
self.showError("Gebruikersnaam of wachtwoord is onjuist")
self.enableLoginBtn(true, buttonText: "Login")
}
})
}catch let parseError{
print(parseError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: \(jsonStr)")
self.enableLoginBtn(true, buttonText: "Login")
}
})
task.resume()
But when i try to test the exact same thing on my iPhone 5s (I have a developer license) it's failing every single time. The error i'm getting is:
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x1742e1e80 {NSUnderlyingError=0x170259230 "The operation
couldn’t be completed. (kCFErrorDomainCFNetwork error -1001.)",
NSErrorFailingURLStringKey=http://10.1.1.33/api/login?email=jejz#kdk.nl&password=sndxbdj,
NSErrorFailingURLKey=http://10.1.1.33/api/login?email=jejz#kdk.nl&password=sndxbdj,
NSLocalizedDescription=The request timed out.}
The last couple days i searched the whole internet for a solution, but i couldn't find any solution.
I'd be really grateful if someone can help me out with this.
Thanks in advance.
Best regards
EDITED ---------------------
Screenshot of the error
I think you might be confused about POST and GET requests.
POST parameters are sent in the Request body, while in the GET request the parameters are sent in the URL.
GET Method parameters example:
/test/demo_form.asp?name1=value1&name2=value2
POST Method parameters example:
POST /test/demo_form.asp HTTP/1.1
Host: w3schools.com
name1=value1&name2=value2
So what you are trying to do, is send the parameters in the URL with the POST request, which is why it doesn't work!
You need to put the parameters in the Request body!
What you need to do is:
1. Change the request URL
var loginUrl = "http://10.1.1.33/api/login"
2. Add the parameters in the Request body
let postString = "email=" + self.email + "&password=" + self.password
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
If you are using iOS 9, this is due to the new Transport security setting that is enabled by default. It blocks all outgoing non https requests. There is a way to turn it off for all requests, so any http request will load. There is also a way to control each url or url wildcard that can load on http.
If you are using http for your login, I suggest you change your server to support SSL and TLS 2.0 (pretty much the standard on most hosts with https) rather than turning it off to load http. Usernames and passwords shouldnt go over http.
If however you need to turn it off for furthering the development until you get a certificate setup, here is how to do it.
Add this to your info.plist file (open it in source code mode, control click on the file and select)
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
If you want to control specific urls, you can use <key>NSExceptionDomains</key>
It's a very tricky problem:
I do a POST request (login) to a server.
The server will answer:
ok Status Code: 200 + JSON Data
error Status Code: 401 + plain/text
Code:
func login (id: String, password: String){
self.responseSerializer = AFJSONResponseSerializer()
self.responseSerializer.acceptableContentTypes = nil
self.responseSerializer.acceptableStatusCodes = NSIndexSet(index: 400)
//self.responseSerializer.acceptableStatusCodes = nil
var param = ["id": lbid, "password": password]
POST(APIURL.URL_LOGIN, parameters: param,
{ (operation : NSURLSessionDataTask!, response : AnyObject!) -> Void in
//var finalResponse : Dictionary = Dictionary<String, String>()
var tmp = response as String
self.defaults.setObject(tmp, forKey: "USERSSID")
self.defaults.setBool(true, forKey: "USERLOGGEDIN")
println("Success login")
}) { (operation : NSURLSessionDataTask!, error : NSError!) -> Void in
println(error)
}
}
It executes the failure blog and I get this error:
Code=-1011 "Request failed: no error (200)" UserInfo=0x7f9fa1534760 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7f9fa15791e0> { URL: https://************ } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 107;
"Content-Type" = "application/json";
Date = "Wed, 04 Mar 2015 21:47:51 GMT";
"Keep-Alive" = "timeout=7, max=150";
Server = Apache;
"Set-Cookie" = "SID=************; expires=Mon, 02-Mar-2020 21:47:51 GMT; path=/;domain=.*********";}},NSErrorFailingURLKey=https://***********,com.alamofire.serialization.response.error.data=< CORRECT POST BODY>, NSLocalizedDescription=Request failed: no error (200)}
If I delete this code:
self.responseSerializer.acceptableStatusCodes = NSIndexSet(index: 400)
Then the app crashes. However the server responses with status code 200...
I don't know how to solve this issue.
Could you help me?
Here I get the correct body. But why not in the normal success blog?
EDIT:
self.responseSerializer.acceptableStatusCodes = NSIndexSet(index: 200)
=> App crashs
self.responseSerializer.acceptableStatusCodes = nil
=> App crashs
self.responseSerializer.acceptableStatusCodes = NSIndexSet(index: 401)
=> App doesn't crash, but executes failure block. Status code in error message is 200 and error data contains the correct POST response body.
=> I could extract the message from the error data... but it's such a simple task. It has to work correctly.
Can't use Alamofire because I want to use ssl certificats!
Final edit:
Don't no why, but the error disappeared by its own.
If you haven't already done so, check out Postman (a Google Chrome app). That's the best way to debug AFNetworking issues, by simulating the same request and making sure the data is coming through properly. A number of times, I've been fighting an issue to then use Postman and discover that it's something the server is doing.
I found something that said:
acceptableStatusCodes
The acceptable HTTP status codes for responses. When non-nil,
responses with status codes not contained by the set will result in an
error during validation.
In Objective C:
self.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
The previous post was very useful to fix it. I was searching more and more but nothing was helped out. I tried of adding different codes and got tired ton's of times. Finally seen the above post, which was really solved the issue. I spent 2 days to find the solution.
Initially got the error with -1011 with 400 error. I solved by using the below:
manager.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndex:400];
Again got different error like this: "200 no error". I solved by using below code:
manager.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
It works!! cool!!
Hence, I advice you you guys to add the set of below code:
manager.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndex:400];
manager.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
Thanks Stackoverflow!!!!