Returning response in AFNETWORKING - ios

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.

Related

how to post uitextfield data in web service on unbutton

i have login screen for company registration, i want to post all uitextfield data on web service on button clicked .
this is my code for button clicked
- (IBAction)Register:(id)sender {
if (_CompanyName.text.length <=0)
{
NSLog(#"enter company name");
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Enter Company Name"
message:nil
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Continue", nil];
[message setAlertViewStyle:UIAlertViewStyleDefault];
[message show];
}
I am beginners in that type of activity so,if anyone have knowledge then please help,thanks.
Very simple posting data to server coding is below
- (IBAction)actionRegister:(id)sender
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:strYourURL]];
[request setHTTPMethod:#"POST"];
//Check The Value what we entered in textField
NSLog(#"the company name is:%#",txtFieldCompanyName.text);
NSLog(#"the email is:%#",txtFieldEmail.text);
NSLog(#"the password is:%#",txtFieldPassword.text);
NSLog(#"the password again is:%#",txtFieldPasswordAgain.text);
//Pass The String to server
NSString *strParameters =[NSString stringWithFormat:#"comapny_name=%#&email=%#&password=%#&password_again=%#",txtFieldCompanyName.text,txtFieldEmail.text,txtFieldPassword.text,txtFieldPasswordAgain.text,nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", strParameters);
//Convert the String to Data
NSData *data1 = [strParameters dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}
}
Use AFNetworking class Here is a link
https://github.com/AFNetworking/AFNetworking
http://www.raywenderlich.com/59255/afnetworking-2-0-tutorial
And some peace of code you will get from this tutorial like
- (IBAction)registerButtonTapped:(id)sender
{
// 1
NSString *string = [NSString stringWithFormat:#"www.yourwebapiurl.php?format=json&username=%#", userNameTextField.text];//and so on
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 3
NSDictionary *responseDict = (NSDictionary *)responseObject;
NSLog(#"You have got the response ");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
It will Help.Thanks

AFNetworking POST not working

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

Json Accelerator and AFNetworking

When the operation is running, I can not enter data in JSON model CREATED BY ACCELERATOR.
Can you tell me what I am doing wrong?
{
[super viewDidLoad];
NSLog(#"you are in a tableViewController");
self.title = #"NavigationOrdini";
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.stampa6x3.com/json.php?azione=ordini"]];
AFJSONRequestOperation* operation;
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:req
success:^(NSURLRequest *request, NSURLResponse *response, id JSON)
{
[[ordiniModel alloc] initWithDictionary:JSON];
}
failure:^(NSURLRequest *request, NSURLResponse *response, NSError
*error, id JSON) {
[self setTitle:#"Dictionary"];
NSLog(#"failed! %d",[error code]);
}];
[operation start];
ordiniModel*test;
NSLog(#"il valore è %#",test.ordini.description);
}
AFJSONRequestOperation is asynchronous, meaning it that the code continues to execute while the rest of the app runs. The completion block are run when the code actually completes.
So try:
NSLog(#"you are in a tableViewController");
self.title = #"NavigationOrdini";
ordiniModel *test; // <-- create variable here
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.stampa6x3.com/json.php?azione=ordini"]];
AFJSONRequestOperation* operation;
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:req
success:^(NSURLRequest *request, NSURLResponse *response, id JSON)
{
test = [[ordiniModel alloc] initWithDictionary:JSON]; // <-- Assign here
NSLog(#"il valore è %#",test.ordini.description);
}
failure:^(NSURLRequest *request, NSURLResponse *response, NSError
*error, id JSON) {
[self setTitle:#"Dictionary"];
NSLog(#"failed! %d",[error code]);
}];
[operation start];

AFNetworking POST cannot return json data

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.

AFNetworking : Cancelled, No Request

Dumb question. I'm just pasting the example AFNetworking code in:
NSURL *url = [NSURL URLWithString:#"https://gowalla.com/users/mattt.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Name: %# %#", [JSON valueForKeyPath:#"first_name"], [JSON valueForKeyPath:#"last_name"]);
} failure:nil];
[operation start];
But, nothing happens. If I output operation to NSLog it looks like the request was cancelled:
<AFJSONRequestOperation: 0x81655f0, state: isExecuting, cancelled: NO request: <NSURLRequest https://gowalla.com/users/mattt.json>, response: (null)>
What am I doing wrong?
Your best bet would be to add a failure block and then inspect the variables provided in that
NSURL *url = [NSURL URLWithString:#"https://gowalla.com/users/mattt.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Name: %# %#", [JSON valueForKeyPath:#"first_name"], [JSON valueForKeyPath:#"last_name"]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"%#", [error localizedDescription]);
}];
[operation start];

Resources