How to send json data in the Http request using AFNetworking - ios

I have to pass data like json format to the server
{"email":"abc#gmail.com","password":"abc"}
and i have used this code but data is not pass to the server please help me..
NSDictionary *dict1=#{#"email": #"biren123#gmail.com"};
NSDictionary *dict2=#{#"password": #"biren"};
services *srv=[[services alloc]init];
NSString *str=#"http://emailsending.in/setting_saver_api/";
NSString *method=#"login.php";
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:dict1 forKey:#"email"];
[dict setValue:dict2 forKey:#"password"];
[srv postToURL:str withMethod:method andParams:dict completion:^(BOOL success, NSDictionary *responseObj)
{
NSLog(#"res :%#",responseObj);
NSLog(#"%d",success);
NSLog(#"Successfully..................");
}];

you can check your link at
https://www.hurl.it/
1)give your http link
2)select your method type "Get" or "Post"
3)add the parameters
and check the response.If you get the same response contact your backend team.

Try this.
1) Convert your dictionary into json using NSJSONSerialization and store it in NSdata.
NSData * incidentData = [NSJSONSerialization dataWithJSONObject: params options:0 error:&err];
2) Post the NSdata containing json to your server

Try this,if this helps
NSString *str = #"http://emailsending.in/setting_saver_api/";
NSString*method = #"login.php";
services *srv=[[services alloc]init];
NSMutableDictionary *dict1 = [NSMutableDictionary dictionary]; [dict1 setValue:#"biren123#gmail.com" forKey:#"email"];
NSMutableDictionary *dict2 = [NSMutableDictionary dictionary]; [dict2 setValue:#"biren" forKey:#"password"];
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:dict1 forKey:#"email"];
[dict setValue:dict2 forKey:#"password"];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:str parameters:dict success:^(NSURLSessionDataTask
*task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
//here is place for code executed in success case
} failure:^(NSURLSessionDataTask *task, NSError *error) {
//here is place for code executed in error case
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error while sending POST"
message:#"Sorry, try again."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
NSLog(#"Error: %#", [error localizedDescription]); }];

Related

Sending Nested NSMutableDictionary as parameters for POST request in AFNetworking 3.0

I am trying to send nested mutable dictionary as parameters in POST request in AFNetworking 3.0.
Here is my sessionmanager settings :
self.requestSerializer = [AFJSONRequestSerializer serializer];
self.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
The dictionary is prepared as below:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
NSNumber *myNumber = [f numberFromString:self.userMobNoTf.text];
NSString *UDID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSMutableDictionary *miniDict = [NSMutableDictionary dictionary];
[miniDict setObject:[NSNumber numberWithInteger:0] forKey:#"ID"];
[miniDict setObject:self.userIDTf.text forKey:#"UserId"];
[miniDict setObject:self.userNameTf.text forKey:#"Name"];
[miniDict setObject:self.userPasswordTf.text forKey:#"Password"];
[miniDict setObject:UDID forKey:#"IMEI"];
[miniDict setObject:#"1.0" forKey:#"AppVersion"];
[miniDict setObject:self.userNameTf.text forKey:#"CreatedBy"];
[miniDict setObject:myNumber forKey:#"MobileNo"];
[miniDict setObject:[NSNumber numberWithInt:1] forKey:#"isActive"];
NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
[paramDict setObject:self.userNameTf.text forKey:#"UserName"];
[paramDict setObject:self.userPasswordTf.text forKey:#"Password"];
[paramDict setObject:self.userIDTf.text forKey:#"UserId"];
[paramDict setObject:myNumber forKey:#"MobileNo"];
[paramDict setObject:UDID forKey:#"Imei"];
[paramDict setObject:[miniDict mutableCopy] forKey:#"Food_UserLogin"];
Here is the POST request:
[appD.sessionManager POST:#"FoodSignUpSave" parameters:paramDict progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
dispatch_async(dispatch_get_main_queue(), ^{
[radialHUD dismiss];
});
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
dispatch_async(dispatch_get_main_queue(), ^{
[radialHUD dismiss];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!" message:error.description delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
});
}];
However, I am getting below error:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x174660fc0 {NSDebugDescription=Invalid value around character 0., NSUnderlyingError=0x174241bc0 "Request failed: bad request (400)"}
If I don't send miniDict in key "Food_UserLogin", I am getting success response but putting this parameter as it being a dictionary creates problem. Any suggestions as to what is wrong?
P.S. I won't want to make any changes on server side.
Fixed the issue by converting miniDict to JSONString and sending this JSONString as value in "Food_UserLogin".
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:miniDict options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[paramDict setObject:jsonString forKey:#"Food_UserLogin"];

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];
}];
}

iOS FacebookSDK image share

I am using the following code to upload an image from my iOS to Facebook.
NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
[params setObject:#"MY TEST MSG..." forKey:#"message"];
[params setObject:UIImagePNGRepresentation(self.editImageView.image) forKey:#"picture"];
[[FBSDKGraphRequest alloc] initWithGraphPath:#"me/photos" parameters:params HTTPMethod:#"POST"] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"uploaded");
} else {
NSLog(#"Graph API Error: %#", [error description]);
}
}];
My app got stuck for couple of minutes and show the error message.
Can any one please help me?
NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:3];
UIImage *picture = FilterImage;
FbGraphFile *graph_file = [[FbGraphFile alloc] initWithImage:picture];
[variables setObject:graph_file forKey:#"file"];
[variables setObject:[NSString stringWithFormat:#"Hello testin"] forKey:#"message"];
[fbGraph doGraphPost:#"me/photos" withPostVars:variables];
NSLog(#"Now log into Facebook and look at your profile & photo albums...");

OAuth Refresh Token Process for salesforce SDK

Can anyone help me with refreshing token on saleforce.
NSDictionary *fields = #{#"grant_type" : #"refresh_token",
#"refresh_token": oauth[#"refreshToken"],
#"client_id": coordinator.credentials.clientId,
#"format": #"json"
};
SFRestRequest *request = [SFRestRequest requestWithMethod:SFRestMethodPOST path:[NSString stringWithFormat:#"%#/services/oauth2/token",[SFAccountManager loginHost]] queryParams:fields];
request.endpoint = [NSString stringWithFormat:#"%#/services/oauth2/authorize", [SFAccountManager loginHost]];
[[SFRestAPI sharedInstance] sendRESTRequest:request failBlock:^(NSError *e) {
NSLog(#"Error %#", e);
} completeBlock:^(NSDictionary* dict) {
NSLog(#"dict");
}];
This is what i am trying to do, but i am getting the following error:
Error Domain=NSURLErrorDomain Code=404 "The operation couldn’t be completed. (NSURLErrorDomain error 404.)" UserInfo=0x7993c670 {Transfer-Encoding=Identity, Content-Type=text/html;charset=UTF-8, Date=Thu, 13 Nov 2014 15:23:36 GMT}
I am not sure what is going wrong.
FYI: Understanding the OAuth Refresh Token Process
This is the request:
endpoint: test.salesforce.com/services/oauth2/authorize
method: POST
path: test.salesforce.com/services/oauth2/token
queryParams: {"grant_type":"refresh_token","refresh_token":"5AsdfdfssdBuiV6yFNukUqDSMUH1tnk39L.x0GFcdqdMhpmQUTu.wv1BNndfglD3SxEZIFUev4i8T2KLkcCOK","format":"json","client_id":"3MVG9dPGzsddfssfdsOQG3p9KW.2hh3Bh5BeEsdfsRlDhxcybG.YRTQC0C0XayvzEw.5.umftLwJpYjYVDE6xgSCgXo"}
I stopped using Salesforce and NSURL Kit instead i use AFHTTPREQUEST
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:#"password" forKey:#"grant_type"];
[dict setObject:#"xxx" forKey:#"client_id"];
[dict setObject:#"xxx" forKey:#"client_secret"];
[dict setObject:#"your user" forKey:#"username"];
[dict setObject:#"password" forKey:#"password"];
[dict setObject:#"json" forKey:#"format"];
[manager POST:#"https://test.salesforce.com/services/oauth2/token" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
}];

how to send array as a parameter in Afnetwoking post method?

hi i need to send a array as a one of the parameter in Afnetworking Query String
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://192.008.0.28/aaa/a/"]];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: #"20", #"Miles", [NSArray arrayWithObjects:#"1",#"2",#"3",nil], #"Interval", nil];
[httpClient postPath:iUpdateNotificationMethod parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[HTTPClient Error]: %#", error.localizedDescription);
}];
But server side we got "Miles":20,"Intervals":null how to fix it
Thanks,
Try This
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:OAuthBaseURL];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithCapacity:0];
for (int i =0; i < [userIDs count]; i++) {
NSString *userID = [[userIDs objectAtIndex:i] objectForKey:#"id"];
NSDictionary *tmpDict = [NSDictionary dictionaryWithObjectsAndKeys:userID , [NSString stringWithFormat:#"ids[%i]",i], nil];
[parameters addEntriesFromDictionary:tmpDict];
}
[client postPath:#"/user"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSData *data = (NSData *)responseObject;
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"jsonStr %#",jsonStr);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self showError];
}
];
Since you're submitting an array, AFNetworking is generating a different parameter name and overloads it with the values you supply. For example, your request generates the following querystring:
Interval[]=1&Interval[]=2&Interval[]=3&Miles=20
This is defined in AFHTTPClient.m in the AFQueryStringPairsFromKeyAndValue function.
If you want to keep the original parameter, you should decide how to convert your NSArray to NSString by yourself. For example, you can do something like [myArray componentsJoinedByString:#","] and then split it back to elements on the server. If you choose this method, beware of using characters that might appear in your actual data.
I believe this will work:
params = #{ #"Miles": #"20", #"Interval": #[#"1",#"2",#"3"] };

Resources