my server side is google compute engine with DJango services as API
this is the code I'm running in xcode IOS 6.1
static NSString *const BaseURLString = #"http://myUrl/";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:BaseURLString
parameters:[self getParameters]
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *returnedData = (NSArray *)responseObject;
[self doSomething:returnedData];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Properties" message:[NSString stringWithFormat:#"%#", error] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
}];
It always fails with Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." but when I call the service from the terminal using curl -datacurl --data "param1=1¶m2=3" http://myUrl/ it works perfect
Try this:
NSURL *url = [NSURL URLWithString:BaseURLString];
and instead of
[manager POST:BaseURLString parameters:[self getParameters]
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *returnedData = (NSArray *)responseObject;
[self doSomething:returnedData];
use
[manager POST:url parameters:[self getParameters]
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *returnedData = (NSArray *)responseObject;
[self doSomething:returnedData];
Related
No visible #interface for 'AFHTTPSessionManager' declares the selector 'POST:parameters:progress:success:failure:'
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.operationQueue.maxConcurrentOperationCount = 10;
[manager POST:[url absoluteString] parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSDictionary *response = (NSDictionary *)responseObject;
NSNumber* remoteAppVersion = [response objectForKey:#"ApplicationVersion"];
[self setLocalAppVersion:remoteAppVersion];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error occured while getAppVersion. Error : %#",error);
[self updateAppCompleted];
}];
}
I upgraded afnetworking 4.0 and got this error in my get and post operations. Can you help me how can i fix this problem
I've to add google autocomplete api in my app but I don't know. I also getting "INVALID REQUEST". I also check developer.google.com but I can't find any solution. I am using AFNetwrok.
Here is my code
NSString *strURL = [NSString stringWithFormat:#"%#key=%#",AutoComplete_URL,GOOGLE_KEY];
NSDictionary *params = #{#"input" : [#"Paris" stringByReplacingOccurrencesOfString:#" " withString:#"+"],#"sensor":#"true"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:strURL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject) {
[APPDELEGATE hideLoadingView];
if ([[responseObject valueForKey:#"status"] isEqualToString:#"OK"]) {
arrAutocomplete = [[responseObject valueForKey:#"predictions"] valueForKey:#"description"];
NSLog(#"AUTO: %#", arrAutocomplete);
}
else{
// [APPDELEGATE showpToastWithTitle:[response valueForKey:#"msg"]];
//[self.tableView setHidden:YES];
}
}
else{
[APPDELEGATE hideLoadingView];
[APPDELEGATE showToastWithTitle:#"Please check your internet connection"];
}
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
[APPDELEGATE hideLoadingView];
[APPDELEGATE showToastWithTitle:#"Something going wrong"];
}];
OUTPUT :-
JSON:
{
predictions = (
);
status = "INVALID_REQUEST";
}
i got it.
NSString *string = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/autocomplete/json?key=%#&types=geocode&input=%#",GOOGLE_KEY,address];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject) {
NSLog(#"%#",responseObject);
}
} 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];
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.
I'm trying to do a POST with action parameter called "#load".
To my webservice is a key need to show results: action:#load
How I can do this using AFNetworking framework? Here a sample of my wrong code:
First the constant declaration:
const NSString *BASE_URL = #"http://www.mywebservice.com/request.php";
Now the code:
-(void)requisitarEventos{
[smartEventos removeAllObjects];
NSString* url = [BASE_URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[SVProgressHUD showWithStatus:#"Loading..." maskType:SVProgressHUDMaskTypeGradient];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"#load",#"action", nil];
[manager POST:url parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[self carregarEventos:responseObject];
[SVProgressHUD dismiss];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
[SVProgressHUD dismiss];
}];
}
I found the answer. The real problem of my code that's my Web Service doesn't give results of Content-Type in "application/json", but in "text/html".
I solve the problem using this code below:
NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:manager.responseSerializer.acceptableContentTypes];
[contentTypes addObject:#"text/html"];
manager.responseSerializer.acceptableContentTypes = contentTypes;
And the full code of my class:
-(void)callEvents{
[smartEvents removeAllObjects];
NSString* url = [NSString stringWithFormat:#"%#myService.php?action=load", BASE_URL];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[SVProgressHUD showWithStatus:#"Loading..." maskType:SVProgressHUDMaskTypeGradient];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:manager.responseSerializer.acceptableContentTypes];
[contentTypes addObject:#"text/html"];
manager.responseSerializer.acceptableContentTypes = contentTypes;
[manager GET:url parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[self carregarEventos:responseObject];
[SVProgressHUD dismiss];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
[SVProgressHUD dismiss];
}];
}
please see this , I make a simple post method with callback ,
POST with URL parameters and JSON body in AFNetworking
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;