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

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

Related

How to send json data in the Http request using AFNetworking

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

Utilizing AFNetworking with YouTube UITableView

I'm hoping someone can help. I am able to list YouTube videos in a tableView without AFNetworking. The code looks something like this:
NSURL *url = [[NSURL alloc] initWithString:#"http://gdata.youtube.com/feeds/api/playlists/PLgw1uRYia2CRrFJW7WT4sKoQxvl_pD0c1?v=2&alt=json&max-results=50&key=AIzaSyA8cyh2w-oa5Z5Wzq6em-ir8YCVF8j1zw4&orderby=published"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSString *jsonString = [[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding];
NSData *jsonData = [jsonString dataUsingEncoding:NSUnicodeStringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingAllowFragments error:nil];
NSDictionary *feed = [[NSDictionary alloc] initWithDictionary:[jsonDict valueForKey:#"feed"]];
videoArray = [NSMutableArray arrayWithArray:[feed valueForKey:#"entry"]];
[self.videolist reloadData];
The images have to load so scrolling is really weird. Therefore, I would like to utilize AFNetworking. Here's the code I have tried:
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *feed = [[NSDictionary alloc] initWithDictionary:[responseObject valueForKey:#"feed"]];
videoArray = [NSMutableArray arrayWithArray:[feed valueForKey:#"entry"]];
NSLog(#"radio==%#",videoArray);
[self.videolist reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
And over cellForRowAtIndexPath, it looks something like this:
NSDictionary *video = videoArray[indexPath.row];
NSString *title = [video valueForKeyPath:#"title.$t"];
cell.videotitle.text = title;
That doesn't work for some reason, even when there are no errors. Help?
The videolist wasn't linked to the table in the Storyboard. The issue is now resolved.

AFNetworking request returns nil

i have a request which returns information from a php web service. I'm having trouble adding this to a array which can be used in my UICollectionView. It seems like whatever i do i cant return the data. I think it is because i'm returning the array before i've added any objects. I've tried placing the NSLog several places, but without luck. What am i doing wrong?
When i place this NSLog(#"%d", imagesArray.count); beyond the request it returns 0.
ViewDidAppear:
-(void)viewDidAppear:(BOOL)animated {
imagesArray = [[NSMutableArray alloc] init];
[self getImages];
}
getImages method:
-(void)getImages {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:#"http://URL.COM" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSString *theTitle = [[json objectForKey:#"response"] valueForKey:#"title"];
NSString *theUrl = [[json objectForKey:#"response"] valueForKey:#"imageUrl"];
[imagesArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:
theTitle, #"title",
theUrl, #"url",
nil]];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
NSLog(#"%d", imagesArray.count);
}
AFNetworking is Asynchronous, you have to place the log inside the success block. Otherwise the array will always be empty.
One good solution would be to pass a block to your getImages function like that
-(void) getImages:(void (^)(BOOL result))callback {
// your code here then you call callback(YES or NO) inside your success or failure block.
}
[self getImages:^(BOOL result){
if(result)
//we got the images, we can now display them etc.
}];

Problems with AFNetworking 2.1.0

I hope this hasn't been asked here...I've done quite a bit of searching on this site but am not really getting anywhere I've been using ASIHTTPRequest to get JSON data, but am now trying to migrate to AFNetworking 2.1.0. I'm using the following:
-(BOOL)getCoordsForAddress:(NSString*) inputAddress {
responseString = [[NSString alloc] init];
// retrieve and urlencode address
NSString *encodedAddress = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)inputAddress, NULL, (CFStringRef)#"!*'();:#&=+$,/?%#[]", kCFStringEncodingUTF8);
// build the geocoding URL
NSString *getLatLonUrl = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=false", encodedAddress];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://maps.googleapis.com"]];
manager.securityPolicy.allowInvalidCertificates = YES;
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[manager GET:getLatLonUrl
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
responseString = [responseObject objectForKey:#"results"];
NSLog(#" Success %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#" Fail %#", error);
}];
return YES;
}
However, when I execute the manager GET routine, nothing is executed, neither the Success or Failure messages are printed out. It's as if that call is getting ignored. What am I doing wrong? Thanks for any assistance!!!

iOS AFNetworking GET/POST Parameters

I want to do a POST request with AFNetworking which contains GET and POST parameters.
I am using this code:
NSString *urlString = [NSString stringWithFormat:#"upload_stuff.php?userGUID=%#&clientGUID=%#",
#"1234",
[[UIDevice currentDevice] identifierForVendor].UUIDString];
NSString *newUrl = #"https://sub.domain.com";
NSURL *baseURL = [NSURL URLWithString:newUrl];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:#"Accept"];
NSDictionary *getParams = [NSDictionary dictionaryWithObjectsAndKeys:
#"1234", #"userGUID",
[[UIDevice currentDevice] identifierForVendor].UUIDString, #"clientGUID",
nil];
NSDictionary *postParams = [NSDictionary dictionaryWithObjectsAndKeys:
[#"xyz" dataUsingEncoding:NSUTF8StringEncoding], #"FILE",
nil];
[httpClient postPath:urlString parameters:postParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error retrieving data: %#", error);
}];
Now I have two questions:
How can I use BOTH GET and POST dictionaries in the same request? For the time, I am integrating the GET dictionary into the URL and using only the POST dictionary ([httpClient postPath:...])
I am getting an error from the server stating that the parameter "FILE" is missing. Unfortunately I can't examine any server logs (not my server). But using a standard NSURLConnection I was able to send requests with the FILE parameter to this server. So what is going wrong here?
Stackoverflow for you:
NSData* sendData = [self.fileName.text dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *sendDictionary = [NSDictionary dictionaryWithObject:sendData forKey:#"name"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:remoteUrl];
NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:#"POST"
path:#"/photos"
parameters:sendDictionary
constructingBodyWithBlock:^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFileData:photoImageData
name:self.fileName.text
fileName:filePath
mimeType:#"image/jpeg"];
}
];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
NSLog(#"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation setCompletionBlock:^{
NSLog(#"%#", operation.responseString); //Gives a very scary warning
}];
[operation start];
By #Igor Fedorchuk from POST jpeg upload with AFNetworking
AFNetworking has no method to setup both GET and POST params.
You have to setup GET params to your url, and use [AFHTTPClient requestWithMethod:path:parameters:] setup POST params.
- (NSURLRequest *)requestForPath:(NSString *)path method:(NSString *)method
{
NSMutableString *pathWithGetParams = [NSMutableString stringWithString:path];
BOOL hasPathContainsQueryChar = [path rangeOfString:#"?"].location != NSNotFound;
[pathWithGetParams appendString:hasPathContainsQueryChar ? #"&" : #"?"];
for (id key in self.getArguments.allKeys)
{
if ([key isKindOfClass:[NSString class]])
{
NSString *value = self.getArguments[key];
if ([value isKindOfClass:[NSString class]])
{
[pathWithGetParams appendString:[[self class] urlEncode:key]];
[pathWithGetParams appendString:#"="];
[pathWithGetParams appendString:[[self class] urlEncode:value]];
[pathWithGetParams appendString:#"&"];
}
}
}
NSString *upperCaseMethod = [method uppercaseString];
BOOL isMethodInGet = [upperCaseMethod isEqualToString:#"GET"];
NSURLRequest *request = [[self shareAFClient] requestWithMethod:method
path:pathWithGetParams
parameters:isMethodInGet ? nil : self.postArguments];
return request;
}
+ (NSString *)urlEncode:(NSString *)stringToEncode
{
return [self urlEncode:stringToEncode usingEncoding:NSUTF8StringEncoding];
}
+ (NSString *)urlEncode:(NSString *)stringToEncode usingEncoding:(NSStringEncoding)encoding
{
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef)stringToEncode,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding));
}
+ (NSString*)urlDecode:(NSString *)stringToDecode
{
return [self urlDecode:stringToDecode usingEncoding:NSUTF8StringEncoding];
}
+ (NSString*)urlDecode:(NSString *)stringToDecode usingEncoding:(NSStringEncoding)encoding
{
return (__bridge_transfer NSString *) CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
(__bridge CFStringRef)stringToDecode,
(CFStringRef)#"",
CFStringConvertNSStringEncodingToEncoding(encoding));
}

Resources