AFNetworking Data Parameter is nil JSON Data - ios

I have an UITableViewController and I'm trying getting JSON data from url with this code but I'm getting error.What should I do ?
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://testurl.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"search_customer",#"page": #""};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSData *jsonData = [NSData dataWithContentsOfFile:string];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"musteri_list"];
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel"];
[self.customerCards addObject:customer];
}
NSLog(#"GET: %#", string);
NSLog(#"POST: %#", parameters);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
This is the error bloc
2015-03-26 14:27:37.656 SaphiraCrm[13770:3881729] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

I think the problem could be in the fact that you are treating the responseObject as if it was NSData, but according to AFNetworking examples, by default AFHTTPRequestOperationManager's responseSerializer is an AFJSONResponseSerializer, so responseObject is already a parsed JSON represented as an NSDictionary (depends on the serializer).
Therefore, the line
NSString *string = [[NSString alloc] initWithData:responseObject
encoding:NSUTF8StringEncoding];
returns nil, which causes the next line
NSData *jsonData = [NSData dataWithContentsOfFile:string];
to raise the exception.
I would suggest that you check responseObject is what you expect it to be and refactor your code accordingly.
...
[manager POST:urlPath
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject) {
NSLog(#"Response is a %# and contains: %#", [responseObject class], responseObject);
// Process responseObject according to its type
...
Note:
It is very likely that the above is just the consequence of a previous mistake in the way you set your seriliazer's configuration, since you set first the acceptableContentType first and then overwrite it with the default one.
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
...
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// this is likely to invalidate the previous, since you overwritting
// the manager's serializer with a new one with default configuration.

Okey I figured Out how can I do this.
There is my code
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://test.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"search_customer",#"page": #""};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"musteri_list"];
NSLog(#"%#",customersArray);
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel"];
[self.customerCards addObject:customer];
}
[self.tableView reloadData];
NSLog(#"GET: %#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Related

AFNetworking response for "key": "\u0001" Not recieved

For my AFNetworking request I expect such "key": "\u0001" response but i am not getting rather I get "key": "". I tried following multiple stack questions but didn't work for me.
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setTimeoutInterval:15];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
manager.securityPolicy.allowInvalidCertificates = true;
manager.securityPolicy.validatesDomainName = false;
[manger.requestSerializer setValue:#"Application/json" forHTTPHeaderField:#"Accept"];
manger.responseSerializer = [AFHTTPResponseSerializer serializer];
[manger GET:url parameters:nil progress:nil success:^(NSURLSessionTask *operation, id responseObject){
NSLog(#"Response REST AP loaded %#", responseObject);
NSMutableDictionary *response = responseObject;
}
It worked in String format when i wrote this line of code
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding];
But now i don't know how to make it to NSDictionary, i also tried converting this to NSDictionary
NSData *webData = [newStr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
This did not work.
Can anyone guide me proper steps how to achieve my expected output.
Thank You
I suggest that you should check responseObject type, for example:
if ([[responseObject class] isSubclassOfClass:[NSDictionary class]]) {
// return responseObject because this is a dictionary
}
else {
NSError *error = nil;
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding];
NSData *webData = [newStr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
return [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
}
NSDictionary* responseDict = [self dataObject:responseData];
use this and then call this method
- (id) dataObject:(NSData*)data
{
return [ NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
Try another ways:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setTimeoutInterval:15];
manager.securityPolicy.allowInvalidCertificates = true;
manager.securityPolicy.validatesDomainName = false;
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:requestURL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response REST AP loaded %#", responseObject);
}

send JSON object in POST request AFNetworking , iOS

I'm using AFNetworking to post data into the web. The information I have is the URI which is baseURL/post_user_info and they want input as A JSON object containing each of the name-value pairs. In the code written below I've set the name-value pair in a dictionary. My question is how to make it's json and send it as input value?
NSString *string = [NSString stringWithFormat:#"%#?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = #{#"input_1": #"hello world",
#"input_2": #"my#you.com",
#"input_3": #"newworldorder"};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
[manager POST:escapedPath parameters:[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
}failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"%#",[error localizedDescription]);
}];
I've updated the code because now I have generated the JSON but if I run the code now it give me Error: 400 which means If input_values is empty, a bad request error will be output.
#interface AFJSONRequestSerializer : AFHTTPRequestSerializer
AFJSONRequestSerializeris a subclass ofAFHTTPRequestSerializerthat encodes parameters as JSON using NSJSONSerialization.
add this AFJSONRequestSerializer is used for send JSON not a Raw Data add this and try once
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
e.g
NSString *string = [NSString stringWithFormat:#"%#?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
/************** karthik Code added ******************/
AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
/************** karthik Code added ******************/
NSDictionary *params = #{#"1": #"hello world",
#"2": #"my#you.com",
#"3": #"newworldorder"};
[manager POST:escapedPath parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
NSLog(#"json == %#", json);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"%#", [error localizedDescription]);
}];
Update Params
NSDictionary *params = #{#"1": #"hello world",
#"2": #"my#you.com",
#"3": #"newworldorder"};
NSMutableDictionary *modify = [NSMutableDictionary new];
[modify setObject:params forKey:#"input_values"];
you get output of

AFNetworking 3 x-www-form-urlencoded post data

I'm trying to post data with x-www-form-urlencoded body.
Posting via postman, it is ok
But i cant do it via afnetworking 3. Here is my code
NSDictionary *parameters = #{#"login" : email,
#"password": password};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
self.requestSerializer = [AFJSONRequestSerializer serializer];
NSString *urlString = [NSString stringWithFormat:#"%#/%#", HTTPBaseRequestURL, appendLoginUrl];
NSLog(#"URL %#\njsonString %#", urlString, jsonString);
[self POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFormData:jsonData name:#"data"];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
onSuccess(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSString *errorDescription = [NSError serverErrorMessageFromData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey]];
NSInteger statusCode = [NSHTTPURLResponse errorCode:(NSHTTPURLResponse*)task.response];
NetworkRequestError *requestError = [[NetworkRequestError alloc] initWithType:
(NSHTTPURLResponse*)task.response ? NetworkRequestErrorTypeServerError : NetworkRequestErrorTypeNoConnection
description:
(NSHTTPURLResponse*)task.response ? errorDescription : nil];
requestError.statusCode = statusCode;
NSLog(#"Error from server: %#, status code = %ld, error type = %lu", requestError.errorDescription, (long)requestError.statusCode, (unsigned long)requestError.type);
onFailure(requestError);
}];
Please, help me to understand how to correctly do this. Thanks!
After commenting I finally found the answer to this. Here's my correctly functioning request now, note the addition of
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
Here's the full code:
NSString *url = [NSString stringWithFormat:#"%#%#",APIBASE,APIUSERENDPOINT];
NSDictionary* parametersDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
username, #"username",
password, #"password",
nil
];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:url parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
try append custom header info ,for example:
[self.requestSerializer setValue:#" application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type];
hope it help for you.
Here . It worked with me . So easy .
NSDictionary* parametersDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"deviceTokenIOS", #"db487c983ebbe7c2fb066d292bb4318175f54ab27b6b9df7871907e1d0ed62ba",
#"message", #"Hello Dunglt",
nil
];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"db487c983ebbe7c2fb066d292bb4318175f54ab27b6b9df7871907e1d0ed62ba", #"deviceTokenIOS", #"Hello Dunglt", #"message", nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:[NSURL URLWithString:url].absoluteString parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];}

UISearchBar displaying data UITableView

I'm trying understand searchbar I have an api And when I send the api 'where' its giving me some data.
But when I tap the return key.I get nothing.
there is my code.
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://test.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"search_record",#"where": self.searchBar.text};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"customer_list"];
NSLog(#"%#",customersArray);
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel"];
[self.customerCards addObject:customer];
}
[self.tableView reloadData];
NSLog(#"GET: %#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
what should I do.
Thanks

Pagination in objective-c UITableViewController

I'm Trying to make pagination with this code.But When I scroll bottom its going 50-60 pages.
What I'm doing wrong.
NSInteger pagesNumber = 1;
- (void)api {
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://test.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"search_customer",#"page": [NSString stringWithFormat:#"%d",pagesNumber]};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"musteri_list"];
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel"];
NSLog(#"%#",customer.tel);
[self.customerCards addObject:customer];
}
[self.tableView reloadData];
NSLog(#"GET: %#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
And This is my scrollViewDidScroll method.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView_ {
if(self.tableView.contentOffset.y >= (self.tableView.contentSize.height - self.tableView.bounds.size.height))
{
pagesNumber = pagesNumber + 1;
[self api];
}
}
So I what should I do in this section.And When I scroll Up data is missing.Its showing currentPageData.
Thanks
Declaration:
NSInteger pagesNumber = 1;
Call "api" method from viewDidLoad, to load data:
- (void)api {
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://test.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"search_customer",#"page": [NSString stringWithFormat:#"%d",pagesNumber]};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"musteri_list"];
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel"];
NSLog(#"%#",customer.tel);
[self.customerCards addObject:customer];
}
[self.tableView reloadData];
NSLog(#"GET: %#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
//instead of using scrollViewDidScroll better use willDisplayCell:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if(self.customerCards.count>1){
if(indexPath.row == self.customerCards.count-1){
pagesNumber=pagesNumber+1;
[self api];
}
}
}

Resources