The network connection was lost.NSURLErrorDomain Code=-1005 - ios

Could anyone help on this?.I am using AFNetworking(1.x) POST method in my app.But frequently i am getting:
'The network connection was lost' error.Error Domain=NSURLErrorDomain Code=-1005 “The network connection was lost.”
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFHTTPResponseSerializer serializer];
op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
op.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
[self SuccessResponse:responseObject:reqType];
NSLog(#"JSON responseObject: %# ",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];

Make sure you have working internet connection.
Try to use below code.
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
NSDictionary *params ; // Pass your POST Parameters here by creating the Dictionary.
[manager POST:#"your api here" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Request failed
// To get failed response data use operation.responseObject
NSLog(#"like request failed %#", error);
}];
Hope this will help you.

Related

unable to get response object

I am unable to get the response from api as the response is quite large. Below code gives internal server error but on rest client runs fine.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = YES;
[manager GET:constantString parameters: nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"POST data JSON returned: %#", responseObject);
jsonArrayNew = responseObject;
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
dispatch_async(dispatch_get_main_queue(), ^{
});
});

AFNetworking response failure block is called instead of success block

AFNetworking response failure block is being called when I get status code 200. How can I make the success be called instead?
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://128.199.94.58/test/bt/client_token.php" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.clientToken = responseObject[#"customerID"];
NSLog(#"Client Token received.");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Handle failure communicating with your server
NSLog(#"Client Token request failed.%#",operation.responseString);
NSLog(#"error code %ld",(long)[operation.response statusCode]);
}];
Look at the value of error. It will tell you why the connection failed. "Failure" in this context has nothing to do with the status code. Returning "404" is still a "success." Failure means you were unable to complete the operation.
use acceptableStatusCodes as follows:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [TimeoutAFJSONRequestSerializer serializer];
NSMutableIndexSet* codes = [[NSMutableIndexSet alloc] init];
[codes addIndex: 200];
manager.responseSerializer.acceptableStatusCodes = codes;
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
}];
I run this code and it work find.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:#"http://128.199.94.58/test/bt/client_token.php" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:nil];
self.clientToken = json[#"customerID"];
NSLog(#"Client Token received.");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Handle failure communicating with your server
NSLog(#"Client Token request failed.%#",operation.responseString);
NSLog(#"error code %ld",(long)[operation.response statusCode]);
}];
responce is:
json:
{
customerID = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiJhMjg2OGVjY2FmZjNjMTQ0M2Y4MTg2MjQ4NDFhZDIyZGM3MWFhOTQ0MmFiMTY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JodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwibWVyY2hhbnRBY2NvdW50SWQiOiI2ejl3eGtkanlyNnQzbmg1IiwiY3VycmVuY3lJc29Db2RlIjoiVVNEIn0sImNvaW5iYXNlRW5hYmxlZCI6ZmFsc2UsIm1lcmNoYW50SWQiOiJ6cWQ5ZHBqZmZkc2s3eG55IiwidmVubW8iOiJvZmYifQ==";
}
It may be work for you.
If you check your error in failure block it clearly say that invalid content type. You need to set the content type of the manager as follows
manager.requestSerializer = [AFJSONRequestSerializer serializer];
try this
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
and in success block
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:manager.responseData options:kNilOptions error:nil];
self.clientToken = dic[#"customerID"];
NSLog(#"Client Token received.");
}

AFNetworking POST Request not working?

This question is already answered at many places but no solution is working for me! I m using code for AFNetworking as following
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFJSONResponseSerializer serializer];
NSDictionary *parameters=#{#"Key1":#"Value1",#"Key2":#"Value2"};
// NSDictionary *parameters = #{#"foo": #"bar"};
[manager POST:#"https://www.MyURL.com/index.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Error :
Error: Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x7a2a03b0 {NSErrorFailingURLKey=https://www.MyURL.com/index.php, NSErrorFailingURLStringKey=https://www.MyURL.com/index.php}
I got no luck for above request.
I do not know what is wrong with my code in POST Request, GET Request is working fine in the AFNetworking.
Try this one :
NSDictionary *dictParameters = parameter here
//create url
NSString *strURL = [NSString stringWithFormat:#"url here"];
NSLog(#"loginurl : %#",strURL);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestOperation *apiRequest = [manager POST:strURL parameters:dictParameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSData *jsonData = (NSData *)responseObject;
NSError * parsedError = nil;
id *value = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&parsedError];
if (parsedError == nil)
{
//Successfull
}
else
{
NSLog(#"wrong while parsing json data");
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error : %#",[error description]);
}];
//start request right now
[apiRequest start];
EDIT : Just Formatted

Afnetworking 2 with parameters

i am really new to IOS developments..i just want to get some JSON response from my web service. when i searched about it i found AFnetworking is good for that. so i downloaded it and did a sample application. but i need to pass some parameters to the service . my service takes two parameters [username and password]. my url like this
http://myweb.mobile.com/WebServices/AppointmentService.asmx/GetValidUser
can anyone please give me some code sample how to pass my parameters to this service to get json response ?
i have tried this code.. but it wont take parameters.. some people telling about AFHTTPClient.. but im using AFN 2.0.. there is no class call AFHTTPCLient here .. i'm so conduced here....please help me
NSURL *url = [NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/textsearch/json?query=restuarants+in+sydney&sensor=false&key=AIzaSyDn9a-EvJ875yMxZeINmUP7CwbO9YT1w2s"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 3
self.googlePlaces = [responseObject objectForKey:#"results"];
[self.tableView reloadData];
// NSLog(#"JSON RESULT %#", responseObject);
self.weather = (NSDictionary *)responseObject;
self.title = #"JSON Retrieved";
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
EDIT :
i have sloved my problem using below code segments...
NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:#"47", #"caregiverPersonId", nil];
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:#"your full url goes here"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", [responseObject description]);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
}
];
Try this
-(void)login
{
NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithCapacity:3];
[dict setObject:_usernameTextField.text forKey:#"userName"];
[dict setObject:_passwordTextField.text forKey:#"password"];
AFHTTPClient *client=[[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:#""]];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:#"Accept" value:#"application/json"];
client.parameterEncoding = AFJSONParameterEncoding;
[client postPath:#"GetValidUser" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *op=(NSDictionary *)responseObject;
NSLog(#"%#",op);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:MESSAGE_EN message:#"Unable to login. Please try again." delegate:self cancelButtonTitle:OK_EN otherButtonTitles:nil, nil];
[alert show];
NSLog(#"error.localizedDescription %#",error.localizedDescription);
}];
}
Note : Please do fill the fields with proper values and try.
dict is the Input postdata
I got this one from somewhere in SO question. See this:
- (IBAction)loginButtonPressed {
NSURL *baseURL = [NSURL URLWithString:#"http://myweb.mobile.com/WebServices/AppointmentService.asmx"];
//build normal NSMutableURLRequest objects
//make sure to setHTTPMethod to "POST".
//from https://github.com/AFNetworking/AFNetworking
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:#"Accept"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[usernameTextField text], kUsernameField,
[passwordTextField text], kPasswordField,
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"http://myweb.mobile.com/WebServices/AppointmentService.asmx/GetValidUser" parameters:params];
//Add your request object to an AFHTTPRequestOperation
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc]
initWithRequest:request] autorelease];
//"Why don't I get JSON / XML / Property List in my HTTP client callbacks?"
//see: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
//mattt's suggestion http://stackoverflow.com/a/9931815/1004227 -
//-still didn't prevent me from receiving plist data
//[httpClient registerHTTPOperationClass:
// [AFPropertyListParameterEncoding class]];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation,
id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", [operation error]);
}];
//call start on your request operation
[operation start];
[httpClient release];
}
Hope this helps .. :)
EDIT
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:[email dataUsingEncoding:NSUTF8StringEncoding]
name:#"email"];
[formData appendPartWithFormData:[pass dataUsingEncoding:NSUTF8StringEncoding]
name:#"password"];
// etc.
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Use below code
NSDictionary *paramDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"first_Object",#"first_Key",#"second_Object",#"second_Key" nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"YOUR_URL_STRING" parameters:paramDictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {Success responce} failure:^(AFHTTPRequestOperation *operation, NSError *error) {failure responce}];
if you want you can set
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = YES;

How to migrate AFHTTPClient, Afnetworking 1.0 to 2.0

My problem is that I have a old code and I dont know how to change it.
I had 1 class called API (AFHTTPClient) I have problems with 2 methods because I dont know how to put them in 2.0:
This:
-(void)commandWithParams:(NSMutableDictionary*)params onCompletion:(JSONResponseBlock)completionBlock
{
NSMutableURLRequest *apiRequest =
[self multipartFormRequestWithMethod:#"POST"
path:kAPIPath
parameters:params
constructingBodyWithBlock: ^(id formData) {
//TODO: attach file if needed
}];
AFJSONRequestOperation* operation = [[AFJSONRequestOperation alloc] initWithRequest: apiRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//success!
completionBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure :(
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:#"error"]);
}];
[operation start];
}
and this:
#pragma mark - init
//intialize the API class with the destination host name
-(API*)init
{
//call super init
self = [super init];
if (self != nil) {
//initialize the object
user = nil;
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:#"Accept" value:#"application/json"];
}
return self;
}
I do a new class called Api, now (AFHTTPRequestOperationManager) is good?
I try with this, but I dont have idea
-(API*)init
{//call super init
self = [super init];
//initialize the object
if (self != nil) {
//initialize the object
user = nil;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFJSONRequestSerializer *a=[AFJSONRequestSerializer serializer];
[a setValue:#"Accept" forHTTPHeaderField:#"application/json"];
[a setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[a setValue:#"content-Type" forHTTPHeaderField:#"text/html"];
[a setValue : # "text / html; charset = UTF-8" forHTTPHeaderField : # "Content-Type" ];
}
return self;
}
-(void)commandWithParams:(NSMutableDictionary*)params onCompletion:(JSONResponseBlock)completionBlock
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = params;
NSURL *filePath = [NSURL URLWithString:#"http://162.243.199.147/mujeresquecorren/iReporter/index.php"];
[manager POST:#"api" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"api" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
NSMutableURLRequest *apiRequest = [NSMutableURLRequest requestWithURL:filePath];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// operationManagerInstance.requestSerializer = requestSerializer;
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:apiRequest];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"http://162.243.199.147/mujeresquecorren/iReporter/index.php" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
} failure:nil];
// AFJSONRequestOperation* operation = [[AFJSONRequestOperation alloc] initWithRequest: apiRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//success!
completionBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure :(
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:#"error"]);
}];
[operation start];
}
and this is one of the errors:
rror: Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=0xa64f980 {NSErrorFailingURLStringKey=api, NSErrorFailingURLKey=api, NSLocalizedDescription=unsupported URL, NSUnderlyingError=0xa782e10 "unsupported URL"}
Please help, im going to be crazy with that and I need that my code works in my app!
Thanks a lot!!!!
It's all there in the error message. "api" isn't a valid URL. You need to either specify an absolute URL, or initialize your request operation manager with a baseURL, using initWithBaseURL:.

Resources