0

i am really new to IOS developments..i just want to get some JSON response from my web service. when i searched about it i found AFnetworking is good for that. so i downloaded it and did a sample application. but i need to pass some parameters to the service . my service takes two parameters [username and password]. my url like this

http://myweb.mobile.com/WebServices/AppointmentService.asmx/GetValidUser

can anyone please give me some code sample how to pass my parameters to this service to get json response ?

i have tried this code.. but it wont take parameters.. some people telling about AFHTTPClient.. but im using AFN 2.0.. there is no class call AFHTTPCLient here .. i'm so conduced here....please help me

 NSURL *url = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/textsearch/json?query=restuarants+in+sydney&sensor=false&key=AIzaSyDn9a-EvJ875yMxZeINmUP7CwbO9YT1w2s"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    // 3
    self.googlePlaces = [responseObject objectForKey:@"results"];

    [self.tableView reloadData];
  //  NSLog(@"JSON RESULT %@", responseObject);

   self.weather = (NSDictionary *)responseObject;
    self.title = @"JSON Retrieved";
    [self.tableView reloadData];


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

EDIT :

i have sloved my problem using below code segments...

 NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:@"47", @"caregiverPersonId", nil];

AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];

AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];

[operationManager POST:@"your full url goes here"
            parameters:parameters
               success:^(AFHTTPRequestOperation *operation, id responseObject) {
                   NSLog(@"JSON: %@", [responseObject description]);
               }
               failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                   NSLog(@"Error: %@", [error description]);
               }
 ];
Darshana
  • 314
  • 2
  • 4
  • 22
  • In 2.0, rather than `AFHTTPClient` you can use `AFHTTPRequestOperationManager`. You can then use `POST` or `GET` (or whatever is appropriate for your web service). – Rob Mar 10 '14 at 06:46
  • thanx a lot with your guidance this link solve my problem http://stackoverflow.com/questions/20047090/post-request-with-afhttprequestoperationmanager-not-working – Darshana Mar 10 '14 at 07:36

3 Answers3

0

I got this one from somewhere in SO question. See this:

- (IBAction)loginButtonPressed {        

    NSURL *baseURL = [NSURL URLWithString:@"http://myweb.mobile.com/WebServices/AppointmentService.asmx"];

    //build normal NSMutableURLRequest objects
    //make sure to setHTTPMethod to "POST". 
    //from https://github.com/AFNetworking/AFNetworking
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
    [httpClient defaultValueForHeader:@"Accept"];

    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            [usernameTextField text], kUsernameField, 
                            [passwordTextField text], kPasswordField, 
                            nil];

    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" 
          path:@"http://myweb.mobile.com/WebServices/AppointmentService.asmx/GetValidUser" parameters:params];

    //Add your request object to an AFHTTPRequestOperation
    AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] 
                                      initWithRequest:request] autorelease];

    //"Why don't I get JSON / XML / Property List in my HTTP client callbacks?"
    //see: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
    //mattt's suggestion http://stackoverflow.com/a/9931815/1004227 -
    //-still didn't prevent me from receiving plist data
    //[httpClient registerHTTPOperationClass:
    //         [AFPropertyListParameterEncoding class]];

    [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];
    [httpClient release];
}

Hope this helps .. :)

EDIT

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

[manager POST:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFormData:[email dataUsingEncoding:NSUTF8StringEncoding]
                                name:@"email"];

    [formData appendPartWithFormData:[pass dataUsingEncoding:NSUTF8StringEncoding]
                                name:@"password"];

    // etc.
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Response: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
Rashad
  • 11,057
  • 4
  • 45
  • 73
  • yes but since im using AFN 2, there is no class called AFHTTPClient... what should i do ? – Darshana Mar 10 '14 at 05:42
  • i have followed it... but i just want to know how to pass my parameters with AFN 2 :( :( please someone help me – Darshana Mar 10 '14 at 05:48
  • that tutorial only uses a url without parameters.. i want to pass my parameters to the web service – Darshana Mar 10 '14 at 05:48
  • yes... i will post my code for others :) thank you for your help..actually it is bit different than you instructed me.. but it helps me to understand :) – Darshana Mar 11 '14 at 07:07
  • In AFNetworking 2.0 you must use AFHTTPRequestOperationManager for post parameter. Isn't it? I just gave you the hint. Great that you solved your problem. :) – Rashad Mar 11 '14 at 07:09
  • yes @Rashad actually it is a few lines of codes... this is really amazing..step by step im learning....i have done the same logic in my android app.. but it was 15 lines of codes for do this... wow i love IOS now :) – Darshana Mar 11 '14 at 07:13
  • Keep coding and keep helping others. Best of luck.. :) – Rashad Mar 11 '14 at 07:14
  • thank you rashad....hey can you tell me how to return the response object in the success block ? – Darshana Mar 11 '14 at 08:23
0

Try this

-(void)login
{
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithCapacity:3];
    [dict setObject:_usernameTextField.text forKey:@"userName"];
    [dict setObject:_passwordTextField.text forKey:@"password"];


    AFHTTPClient *client=[[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:@""]];

    [client registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [client setDefaultHeader:@"Accept" value:@"application/json"];
    client.parameterEncoding = AFJSONParameterEncoding;

    [client postPath:@"GetValidUser" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSDictionary *op=(NSDictionary *)responseObject;
         NSLog(@"%@",op);

    }
             failure:^(AFHTTPRequestOperation *operation, NSError *error) {

                     UIAlertView *alert=[[UIAlertView alloc]initWithTitle:MESSAGE_EN message:@"Unable to login. Please try again." delegate:self cancelButtonTitle:OK_EN otherButtonTitles:nil, nil];
                     [alert show];

                     NSLog(@"error.localizedDescription %@",error.localizedDescription);
                              }];

}

Note : Please do fill the fields with proper values and try. dict is the Input postdata

Lithu T.V
  • 19,955
  • 12
  • 56
  • 101
  • 1
    This is AFNetworking 1.x. In 2.x you can use `AFHTTPRequestOperationManager`. – Rob Mar 10 '14 at 06:48
  • can you please update the answer according to AFN 2 ? – Darshana Mar 10 '14 at 07:19
  • thank you with your guidance i have solve this issue with this link http://stackoverflow.com/questions/20047090/post-request-with-afhttprequestoperationmanager-not-working – Darshana Mar 10 '14 at 07:37
0

Use below code

NSDictionary *paramDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"first_Object",@"first_Key",@"second_Object",@"second_Key" nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:@"YOUR_URL_STRING" parameters:paramDictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {Success responce} failure:^(AFHTTPRequestOperation *operation, NSError *error) {failure responce}];

if you want you can set

manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = YES;
Konda
  • 123
  • 1
  • 10