Posting data on server in ios app (objective-c) - ios

This is the method I am using to post address on the server.
But when click the button it goes to stopActivityIndicatorInView .
But not posting the data and it only shows UIalertview. I need some help where I am doing wrong.
when I change parameters to "user_id" it goes to the exception.
-(void)ServiceAddress
{
NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
[Utils startActivityIndicatorInView:self.view withMessage:#"Please wait...."];
NSString *strurl = [NSString stringWithFormat:#"URL"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setObject:[[NSUserDefaults standardUserDefaults] objectForKey:#"userid"] forKey:#"userid"];
[parameters setObject:_txtcity.text forKey:#"city"];
[parameters setObject:_txthome.text forKey:#"house_no"];
[parameters setObject:_txtflat.text forKey:#"locality"];
[parameters setObject:_txtpincode.text forKey:#"pin_code"];
[parameters setObject:_txtCurrentLocation.text forKey:#"address"];
[parameters setObject:_txtmobile.text forKey:#"mobile"];
[manager POST:strurl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary* data1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSLog(#"JSON: %#", data1);
if([[[data1 objectForKey:#"commandResult"] objectForKey:#"success"]integerValue]==1)
{
[Utils stopActivityIndicatorInView:self.view];
UIStoryboard *story=[UIStoryboard storyboardWithName:#"Main" bundle:nil];
MyAddressVC *view=[story instantiateViewControllerWithIdentifier:#"MyAddressVC"];
[self.navigationController pushViewController:view animated:NO];
}
else
{
[Utils stopActivityIndicatorInView:self.view];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#""
message:#"go back"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
[Utils stopActivityIndicatorInView:self.view];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}];
}
these are the parameters I got from server.
$userId = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : '';
$mobile = isset($_REQUEST['mobile']) ? $_REQUEST['mobile'] : '';
$houseNo = isset($_REQUEST['house_no']) ? $_REQUEST['house_no'] : '';
$street = isset($_REQUEST['street']) ? $_REQUEST['street'] : '';
$locality = isset($_REQUEST['locality']) ? $_REQUEST['locality'] : '';
$city = isset($_REQUEST['city']) ? $_REQUEST['city'] : '';
$state = isset($_REQUEST['state']) ? $_REQUEST['state'] : '';
$pinCode = isset($_REQUEST['pin_code']) ? $_REQUEST['pin_code'] : '';
$latitude = isset($_REQUEST['latitude']) ? $_REQUEST['latitude'] : '';
$longitude = isset($_REQUEST['longitude']) ? $_REQUEST['longitude'] : '';

If it's displaying the alert view, it means the request wasn't successful, double check your parameters, for example for user id, you have missed the underscore so it should be like this: "user_id" instead of "userid"

Related

Upload 5 images to server using AFNetworking [duplicate]

This question already has answers here:
AFNetworking multiple files upload
(3 answers)
Closed 6 years ago.
I used Afnetworking in my app,I need to post 5 images to server, 5 images as array, this array was one of my **request parameters.
this is correct way or wrong one, there is any one more performance than it ? -
(IBAction)sPActionButton:(id)sender {
NSUserDefaults *def=[NSUserDefaults standardUserDefaults];
NSString * language=[def objectForKey:#"Language"];
NSString * deviceToken=[def objectForKey:#"dT"];
[par setObject:deviceToken forKey:#"dT"];
NSString *check=[def objectForKey:#"Log"];
[par setObject:check forKey:#"aT"];
//---------------------------------------------
NSString * apiKey=APIKEY;
[par setObject:apiKey forKey:#"aK"];
[par setObject:language forKey:#"lG"];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:10];
for (int x=0; x<_chosenImages.count; x++) {
NSData *imageData = UIImageJPEGRepresentation(_chosenImages[x], 0.5);
NSLog(#"%#",imageData);
NSString *str=[Base64 encode:imageData];
[images addObject:str];
}
NSLog(#"%#",images);
[par setObject:images forKey:#"image[array]"];
if ([self validateAllFields]) {
NSLog(#"par = %#",par);
//-----------------------------------------------
[MBProgressHUD showHUDAddedTo:self.view animated:NO];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:[NSString stringWithFormat:#"%#/sellPrp?",BASEURl] parameters:par
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Data"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
[MBProgressHUD hideHUDForView:self.view animated:NO];
}];
}
}
- (void)prepareForImagePosting
{
if (imageCount < self.arrAllPostImages.count)//arrAllPostImages array contains images for posting and imageCount acts as iterator
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init]; //Prepare the dictionary which contains image for posting
[dict setObject:#"1" forKey:#"upload"];
[dict setObject:[[self.arrAllPostImages objectAtIndex:imageCount]objectForKey:#"SelectedPhoto"] forKey:#"post_image"];
[self postImage:dict];
}
else
return;
}
- (void)postImage: (NSMutableDictionary *)dictPostImages
{
NSError *error = nil;
NSString *url = POSTIMAGELINK;
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setObject:[dictPostImages objectForKey:#"upload"] forKey:#"upload"];
NSData *jsonRequestDict = [NSJSONSerialization dataWithJSONObject:postDict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonCommand = [[NSString alloc] initWithData:jsonRequestDict encoding:NSUTF8StringEncoding];
NSLog(#"***jsonCommand***%#",jsonCommand);
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:jsonCommand,#"requestParam", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if (isEnteredInFailureBlock == NO)
{
//here Image is posted
NSData *postPicData=UIImageJPEGRepresentation([dictPostImages objectForKey:#"post_image"], 0.5) ;
[formData appendPartWithFileData:postPicData
name:#"post_image"
fileName:[NSString stringWithFormat:#"image%d.jpg",imageCount]
mimeType:#"image/*"];
}
else
{
}
} success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error = nil;
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
NSMutableDictionary *jsonResponseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSLog(#"Response Dictionary:: %#",jsonResponseDict);
if ([[jsonResponseDict objectForKey:#"status"] intValue] == 1)
{
if (isEnteredInFailureBlock == NO)
{
[self.arrSuccessfullyPostedImagesDetails addObject:jsonResponseDict];
if (appDel.successfullImgPostingCount == appDel.totalPostingImagesCount)
{
}
else
{
appDel.successfullImgPostingCount++;
imageCount++;
[self prepareForImagePosting];
}
}
else
{
self.arrSuccessfullyPostedImagesDetails = [[NSMutableArray alloc]init];
appDel.successfullImgPostingCount = 0;
appDel.totalPostingImagesCount = 0;
imageCount = 0;
return;
}
}
else
{
self.arrSuccessfullyPostedImagesDetails = [[NSMutableArray alloc]init];
appDel.successfullImgPostingCount = 0;
appDel.totalPostingImagesCount = 0;
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Request Error: %#", error);
isEnteredInFailureBlock = YES;
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Posting Unsuccessful" delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
// if image is not successfully posted then the server is informed with #"upload" #"0" so that the entire post is deleted from server
NSMutableDictionary *failureDict = [[NSMutableDictionary alloc]init];
[failureDict setObject:#"0" forKey:#"upload"];
[self postImage:failureDict];
}];
}

Anonymous response during service consumption iOS

I am facing anonymous behavior of service response. Sometime service fetched well and sometimes it gives an error message "A server with specified host name can't be found". I am using AFNetworking. Same service worked very well in android platform. Is there any better way to fetch them accurately in iPhone.
here is my piece of code:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSDictionary *params = #{#"email" : txtEmail.text,
#"password" : txtPassword.text,
};
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:#"http://somelink/someuser.svc/login" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", operation.responseString);
NSDictionary *responseDict = responseObject;
NSLog(#"%#",[responseDict valueForKey:#"result_code"]);
if ([[responseDict valueForKey:#"result_code"] isEqualToString:#"1"]) {
NSDictionary *data = [responseObject objectForKey:#"result_data"];
NSLog(#"%#",[data objectForKey:#"email"]);
[[NSUserDefaults standardUserDefaults]setObject:[data objectForKey:#"user_id"] forKey:#"UserId"];
NSString *query = [NSString stringWithFormat:#"insert into userMaster (user_id, name_first, name_last, email, password, image, gender, rec_limit, total_followers, total_following, is_brand, category) values ('%#','%#','%#','%#','%#','%#','%#',%d,'%#','%#',%d,%d)",[data objectForKey:#"user_id"],[data objectForKey:#"name_first"],[data objectForKey:#"name_last"],[data objectForKey:#"email"],[data objectForKey:#"password"],[data objectForKey:#"image"],[data objectForKey:#"gender"],[[data objectForKey:#"rec_limit"]intValue],[data objectForKey:#"total_followers"],[data objectForKey:#"total_following"],[[data objectForKey:#"is_brand"]intValue],[[data objectForKey:#"category"]intValue]];
// NSLog(#"%#",[data objectForKey:#"intrests"]);
NSLog(#"%#",query);
int n = [service insertUpdateDeleteWithQuery:query inDatabase:#"WaveDb.sql"];
NSLog(#"%d",n);
NSArray *arr = [data objectForKey:#"intrests"];
for (int i = 0; i < arr.count; i++) {
NSLog(#"%#",[arr objectAtIndex:i]);
query = [NSString stringWithFormat:#"insert into userCategory (user_id, cat_id) values ('%#','%#')",[[NSUserDefaults standardUserDefaults]objectForKey:#"UserId"],[arr objectAtIndex:i]];
[service insertUpdateDeleteWithQuery:query inDatabase:[DataClass databaseName]];
}
dispatch_async(dispatch_get_main_queue(), ^{
[(AppDelegate *)[[UIApplication sharedApplication]delegate]hideProgress];
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:#"login"];
WallViewController *main = [self.storyboard instantiateViewControllerWithIdentifier:#"wallView"];
[self.navigationController pushViewController:main animated:YES];
});
}
else {
[(AppDelegate *)[[UIApplication sharedApplication]delegate]hideProgress];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Invalid username and password" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
} failure:^(AFHTTPRequestOperation operation, NSError error) {
NSLog(#"Error: %#", error);
dispatch_async(dispatch_get_main_queue(), ^{
[(AppDelegate *)[[UIApplication sharedApplication]delegate]hideProgress];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Some technical error occured. Try later." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
});
}];
});
check reachability before any code execution is solved my problem.

AFNetworking fail with response.statusCode 0

I want to get address from latitude and longitude with GoogleGEO CODING (EX URL = http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true_or_false )
So I want to get JSON from that page by AFNetworking.
It's my code below :
IBAction)reLocation:(UIButton*)sender
{
if(sender.tag==1)
{
NSArray *gpsValue = [self getGPS];
float lat = [[gpsValue objectAtIndex:0] floatValue];
float lon = [[gpsValue objectAtIndex:1] floatValue];
NSString *string = [NSString stringWithFormat:#"%#%#,%#&sensor=true_or_false",GEOCODING_URL,[NSString stringWithFormat:#"%f", lat],[NSString stringWithFormat:#"%f",lon]]; // NSString *str = [NSString stringWithFormat:#"%f", myFloat];
NSLog(string);
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"AFNetworking success");
NSDictionary *location = (NSDictionary *)responseObject;
// 3
self.title = #"JSON Retrieved";
//[self.tableView reloadData];
NSLog(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"AFNetworking failure");
switch (operation.response.statusCode) {
case 400:
// Do stuff
NSLog(#"error 400");
break;
default:
NSLog([NSString stringWithFormat:#"%ld",(long)operation.response.statusCode]);
break;
}
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}}
But when I click my button, always afnetworking fails and log shows 0 for status code.
I also got url log that i put in
i already checked that url is not problem (it shows json in working order)
I debug with simulator!
Is there something I miss ?

AFNetworking - AFHTTPRequestOperationManager does not return data

I am using AFHTTPRequestOperationManager for login.
- (IBAction)loginAction
{
[TGProjectHandler clearCookies];
NSDictionary *params = #{#"Email": _email.text,
#"Password": _password.text,
#"IsRemember": #"true",
#"ReturnUrl": #"",
#"UserId": #0,
#"OutResponse": #0};
[_sharedHandler.requestManager POST:TGURL_LOGIN
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *e;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[operation.responseString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&e];
NSLog(#"%#\n\n%#", jsonDict, responseObject);
NSString *outResponse = responseObject[#"Object"][#"OutResponse"];
if (outResponse.integerValue == 1){
NSLog(#"login successful: %#", outResponse);
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"User_Logged_In"];
[TGProjectHandler saveCookiesToDefaults];
[self performSegueWithIdentifier:#"HomePage" sender:self];
}else
{
[[[UIAlertView alloc] initWithTitle:#"Login Failed" message:#"Invalid credentials" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[TGProjectHandler dismissHUD];
[[[UIAlertView alloc] initWithTitle:#"Login Failed" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
}];
}
The service function returns UserID, but this is what I am getting in response while NSLog.
NSLog(#"%#\n\n%#", jsonDict, responseObject);
Object = {
OutResponse = 1;
ReturnUrl = "<null>";
};
Success = 1;
}
{
Object = {
OutResponse = 1;
ReturnUrl = "<null>";
};
Success = 1;
}
Why is UserId not coming in response?
By looking at your code I guess the problem might be content type in your request. Check if your content type is set properly.
For Example -
[_sharedHandler.requestSerializer setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
Also you can change response serializer to AFJSONResponseSerializerwhich will automatically convert your response to dictionary or array.
_sharedHandler.responseSerializer = [AFJSONResponseSerializer serializer];

Authenticate screen xcode 5 ios 7

I am new in ios and I am stuck for days about how to make a login screen and let the user connect to the application.
Can anyone help me or give me a tutorial because I'm searching for days without finding anything. I am getting my user from a web service.
-(void)listeDesUtilisateurs{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://127.0.0.1:8888/services/user.php" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON out : %#",responseObject);
userTab = (NSArray *) [responseObject valueForKeyPath:#"items"];
NSLog(#"nombre des elements : %d", userTab.count );
for (User *user in userMutTab) {
[user.managedObjectContext deleteObject:user];
}
[self.managedObjectContext save:nil];
for (int i=0; i<userTab.count; i++) {
User *user = [NSEntityDescription insertNewObjectForEntityForName:#"User"
inManagedObjectContext:self.managedObjectContext];
NSDictionary *consultationDic = [userTab objectAtIndex:i];
user.nom_utilisateur = [consultationDic objectForKey:#"username"];
user.mot_de_passe = [consultationDic objectForKey:#"password"];
user.nom_prenom = [consultationDic objectForKey:#"nom_prenom"];
user.nom_prenom_en_arabe = [consultationDic objectForKey:#"nom_prenom_arabe"];
user.specialite = [consultationDic objectForKey:#"specialite"];
user.specialite_en_arabe = [consultationDic objectForKey:#"specialite_en_arabe"];
user.gsm =[consultationDic objectForKey:#"gsm"];
user.telephone_cabinet = [consultationDic objectForKey:#"telephone_cabinet"];
user.adresse = [consultationDic objectForKey:#"adresse"];
user.adresse_en_arabe =[consultationDic objectForKey:#"adresse_arabe"];
}
NSError *error;
if (![self.managedObjectContext save:&error])
{
NSLog(#"Problème d'enregistrement : %#",[error localizedDescription ] );
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error : %#",error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"error"
message:[NSString stringWithFormat:#" %#",error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}];
}

Resources