I want to make a request with POST method and after that I want them to return the json data or NSDictionary, but they can only return the string when it succeed
Like NSString *response = [operation responseString];
Anyone know how to make them return NSdictionary instead of NSString?
-(IBAction)SubmitLogin:(id)sender{
NSLog(#"Login");
// NSLog(#"%#",username);
//START FUNGSI UNTUK POST, PUT, DELETE
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:signinUrl];
[httpClient defaultValueForHeader:#"Accept"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"someuser", #"username",
#"somepassword",#"password",
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#""
parameters:params];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[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];
I was trying to send JSON object and getting back JSON data and parse it
NSURL *url = [NSURL URLWithString:#"https://MySite.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
//[httpClient setParameterEncoding:AFJSONParameterEncoding];
//[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"Ans", #"name",
#"29", #"age", nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"/testJSONReturn.php"
parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"DATA: %#", [JSON valueForKeyPath:#"data"]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failure Because %#",[error userInfo]);
}];
[operation start];
Might help
This is what I use, feel free to fit it to your needs:
-(void) loginWithUserID:(NSString*)usrID User:(NSString*)usr Password:(NSString *)psw Sender:(id)sender
{
if ([sender respondsToSelector:#selector(startLoading)]){
[sender performSelector:#selector(startLoading)];
}
baseURL = [NSString stringWithFormat:
#"http://xxx.xxx.xxx.xxx/test/service.svc/weblogin"];
NSString* serviceURL = [NSString stringWithFormat:
#"%#?userID=%#&user=%#&password=%#",baseURL,usrID,usr,psw;
NSURL *url = [NSURL URLWithString:[serviceURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.LoginOK = [JSON valueForKeyPath:#"LoginOK"];
if (LoginOK.intValue == 1) {
NSDictionary *usrData = [JSON valueForKeyPath:#"userData"];
userData = [[UserData alloc]init];
[userData readFromJSONDictionary:usrData];
NSLog(#"Userdata: %#",userData);
if ([sender respondsToSelector:#selector(loginSuccessful:)])
{
[sender performSelector:#selector(loginSuccessful:)];
}
}else{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"No Correct Login Credentials" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
;}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
if ([sender respondsToSelector:#selector(stopLoading)]){
[sender performSelector:#selector(stopLoading)];
}
[[[UIAlertView alloc] initWithTitle:#"Error"
message:#"Loginservice not available! Check your connection!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil] show];
NSLog(#"Error: %#", error);
}];
[operation start];
};
EDIT: Oh and use a
-(void)readFromJSONDictionary:(NSDictionary *)d
{
[self setProperty1:[d objectForKey:#"property1"]];
}
method to get all the properties out of that dictionary into a custom class.
Related
My code is below:
NSString *urlString = [[NSString stringWithFormat:#"/players?skip=%ld",(long)skipSize] DVURL];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//[request set]
[request setValuesForKeysWithDictionary:[filter filteringDictionary]];
AFHTTPRequestOperation *operation =
[[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"responseObject %#", responseObject);
totalPages = ([[responseObject
objectForKey:#"count"] intValue] / 20);
NSLog(#"%#",[responseObject objectForKey:#"players"]);
for (NSDictionary *playerDict in [responseObject objectForKey:#"players"]) {
DVPlayer *player = [[DVPlayer alloc] initWithDictionary:playerDict];
if (![self.playerArray.players containsObject:player]) {
[self.playerArray.players addObject:player];
}
}
[playerCollectionView reloadData];
} failure:
^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
[[[UIAlertView alloc]
initWithTitle:#"Error fetching players!"
message:#"Please try again later"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}];
[operation start];
When I use AFHTTPRequestOperationManager, I used NSDictionary as parameter for GET method.
So I thought [request setValuesForKeysWithDictionary:[filter filteringDictionary]]; would be corresponding.
But I got an error :
setValue:forUndefinedKey:]: this class is
not key value coding-compliant for name(ex)
I architected the parameter is NSDictionary for convenience...
Can't I set parameter as NSDictionary when using AFHTTPRequestOperation , not AFHTTPRequestOperationManager?
Help me please
AFHTTPRequestOperation takes an NSURLRequest as an init parameter. As such, you need to handle the serialization yourself, append it to your url, and then encode the url:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[yourUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
Just one more reason why AFHTTPRequestOperationManager is easier ;)
I have run into a strange situation when creating trying to save the objects from an array to a rails backend. I have two array and I have no problem saving each one on its own. The problem is that I am also creating a table that is a combination of the two objects. So it would be best to create an action for index path 1 for both arrays, index path 2 for both arrays and so on. The arrays will always have the same amount of objects inside of them. This way, for index path one, it could save both of them and make the combination table at the same time, thus eliminating my problem. My second problem is that I have no idea how to create a block of code that executes for an index path of multiple array. I know this is probably quite weird, but any help would be great.
Here is how I was doing it for every object of a single array:
-(void)savePeroid {
[self.periodArray enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
if (self.navigationItem.rightBarButtonItem.tintColor == [UIColor redColor]) {
NSURL *url = [NSURL URLWithString:#"http://localhost:3000/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
object, #"period[name]",
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"api/period"
parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"ID: %#", [JSON valueForKeyPath:#"id"]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failure Because %#",[error userInfo]);
}];
[operation start];
}
}];
[self saveSubject];
}
How about this:
-(void)savePeroid {
for (int i=0; i<self.periodArray.count; i++) {
id periodObject = self.periodArray[i];
id otherArrayObject = self.otherArray[i];
if (self.navigationItem.rightBarButtonItem.tintColor == [UIColor redColor]) {
NSURL *url = [NSURL URLWithString:#"http://localhost:3000/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
periodObject, #"period[name]",
otherArrayObject, #"other[something]",
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"api/period"
parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"ID: %#", [JSON valueForKeyPath:#"id"]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failure Because %#",[error userInfo]);
}];
[operation start];
}
};
[self saveSubject];
}
I am following this tutorial to learn AfNetworking in IOS
And I am using the following function to get the response from the server:
{
// 1
NSString *weatherUrl = [NSString stringWithFormat:#"%#weather.php?format=json", BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
// 3
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//Success
}
// 4
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[NSString stringWithFormat:#"%#",error]
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
}];
// 5
[operation start];
}
What I want is to write a function which will returns the response as a NSString after getting response. I don't know the syntax.Can anybody help me ?
Try this
- (void)getResponse:(void (^)(id result, NSError *error))block {
NSString *weatherUrl = [NSString stringWithFormat:#"%#weather.php?format=json", BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
// 3
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//Success
block(JSON,nil); //call block here
}
// 4
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[NSString stringWithFormat:#"%#",error]
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
}];
// 5
[operation start];
}
calling
[self getResponse:^(id result, NSError *error) {
//use result here
}];
hope this helps
You could simply log it like this where //success is
NSLog(#"%#", JSON);
Or if you wanted it in a string format then:
[NSString stringWithFormat:#"JSON response is %#", JSON];
Hope this helps.
I am trying to make a POST request using AFNetworking. I went through SO and found that I need to include httpClient.parameterEncoding = AFJSONParameterEncoding
It still doesn't work even after making that change. Anything else I am missing ? Here is the code
NSDictionary *subDictionaryUsers = [[NSDictionary alloc]initWithObjectsAndKeys:myObject.name,#"name", myObject.topic_description,#"description", nil];
NSString *_restPath = [NSString stringWithFormat:#"spaces.json/auth_token=%#",myObject.auth_token];
NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:subDictionaryUsers,#"space",nil];
myAppAFNClient *httpClient = [myAppAFNClient sharedClient];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:_restPath parameters:params];
httpClient.parameterEncoding = AFJSONParameterEncoding;
[httpClient getJsonResponse:request notificationString:#"add.hydramixer.topics"];
myAppAFNClient.m
-(void)getJsonResponse:(NSURLRequest *)_request notificationString:(NSString *)notifString{
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:_request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
if([notifString length] != 0){
// handling success
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
// handling errors
}];
[operation start];
}
I'm getting this response in error.userInfo while making a POST request from AFNetworking.
Can anyone tell either I'm missing anything obvious or something need to fix at my server end?
Request Failed with Error: Error Domain=AFNetworkingErrorDomain
Code=-1016 "Expected content type {(
"text/json",
"application/json",
"text/javascript" )}, got text/html" UserInfo=0x6d7a730 {NSLocalizedRecoverySuggestion=index test,
AFNetworkingOperationFailingURLResponseErrorKey=, NSErrorFailingURLKey=http://54.245.14.201/,
NSLocalizedDescription=Expected content type {(
"text/json",
"application/json",
"text/javascript" )}, got text/html, AFNetworkingOperationFailingURLRequestErrorKey=http://54.245.14.201/>}, {
AFNetworkingOperationFailingURLRequestErrorKey = "http://54.245.14.201/>";
AFNetworkingOperationFailingURLResponseErrorKey = "";
NSErrorFailingURLKey = "http://54.245.14.201/";
NSLocalizedDescription = "Expected content type {(\n \"text/json\",\n \"application/json\",\n
\"text/javascript\"\n)}, got text/html";
NSLocalizedRecoverySuggestion = "index test"; }
And I'm using this code;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"Ans", #"name",
#"29", #"age",
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:#"/" parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Success");
NSLog(#"%#",JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
NSLog(#"Failure");
}];
[operation start];
[operation waitUntilFinished];
By default, AFJSONRequestOperation accepts only "text/json", "application/json" or "text/javascript" content-types from server, but you are getting "text/html".
Fixing on server would be better, but you can also add "text/html" content type as acceptable in your app:
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:#"text/html"]];
It worked for me, hope this helps!
Did you send this POST request by AFHTTPClient? If so, you need to set operation class for it:
AFHTTPClient * client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://localhost:8080"]];
// ...
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:#"Accept" value:#"application/json"];
// ...
// EDIT: Use AFHTTPClient's POST method
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"Ans", #"name",
#"29", #"age", nil];
// POST, and for GET request, you need to use |-getPath:parameters:success:failure:|
[client postPath:#"/"
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"RESPONSE: %#", responseObject);
// ...
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (error)
NSLog(#"%#", [error localizedDescription]);
// ...
}
Set your values in this code and check if it works for you
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:kBASEURL]];
NSString *_path = [NSString stringWithFormat:#"groups/"];
_path = [_path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%s %#",__PRETTY_FUNCTION__,_path);
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:_path
parameters:postParams];
[httpClient release];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
if ([JSON isKindOfClass:[NSArray class]] || [JSON isKindOfClass:[NSDictionary class]]) {
completed(JSON);
}
else {
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#" response %# \n error %# \n JSON %#",response,error,JSON);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
errored(error);
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];