0

I'm trying to POST request using AFNetworking 3.0.

So far i did not find the exact answer for this issue. Either i don't understand or some of the code is deprecated.

Error is "dataTaskWithRequest is deprecated"

I have this two (2) textfield that need to be post into web server.

1. email

2. pw

So far it didn't work. The current code as below

#import "ViewController.h"
#import "AFNetworking.h"

@interface ViewController ()
@end

@implementation ViewController
@synthesize email,pw;

- (IBAction)sendData:(id)sender {

    NSString *URLString = @"http://localhost/test.php";     
    NSDictionary *parameters =@{@"email" : @"pw"};   
    NSError *error;       

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];   
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];  

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];   
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:nil error:nil];

    req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"email"] longValue];
    [req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Accept"];
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

        if (!error) {
            NSLog(@"Reply JSON: %@", responseObject);

            if ([responseObject isKindOfClass:[NSArray class]]) {

                NSLog(@"Response == %@",responseObject);

            }
        } else {
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
        } 
    }]resume];
}
@end
Cœur
  • 37,241
  • 25
  • 195
  • 267
AlotJai
  • 147
  • 4
  • 18
  • What is this?:`req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"email"] longValue];` – Ronak Chaniyara Jan 09 '17 at 05:07
  • Please look at the accepted answer of [this](http://stackoverflow.com/questions/34561215/afnetworking-3-0-migration-how-to-post-with-headers-and-http-body). – Gour Jan 09 '17 at 05:09

3 Answers3

1
 NSString *URLString = @"http://localhost/test.php";     
    NSDictionary *parameters =@{@"email":@"pass email id" @"pw":@"pass password"}; 
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        manager.responseSerializer=[AFHTTPResponseSerializer serializer];

        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

        manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"application/x-www-form-urlencoded"];

        [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)  {
 NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
                                                             options:kNilOptions
                                                               error:&error];
}

          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

              UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Aleksi"

                                                                                       message:[error localizedDescription]

                                                                                preferredStyle:UIAlertControllerStyleAlert];

              UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"

                                                                 style:UIAlertActionStyleDefault

                                                               handler:nil]; //You can use a block here to handle a press on this button

              [alertController addAction:actionOk];
              NSLog(@"error=%@",error );
              CFRunLoopStop(CFRunLoopGetCurrent());

          }];

download Afnetworking 3.0 in this link https://github.com/AFNetworking/AFNetworking

Jigar
  • 1,801
  • 1
  • 14
  • 29
1

try this code, i guess it will solve your issue

NSString *url = @"http://localhost/test.php";     
NSDictionary* parametersDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                          email, @"email",
                          password, @"pw",
                          nil
                          ];

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
//you can change timeout value as per your requirment
        [manager.requestSerializer setTimeoutInterval:60.0];
    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);
}];
Developer
  • 822
  • 9
  • 23
1

Simply do like following way in AFNetworking 3.0 :

        - (IBAction)sendData:(id)sender {
NSString *Loginurl = [NSString stringWithFormat:Your_URL_is_here];


        NSDictionary *params = @{@"user_name":username.text,

                                 @"password":password.text,

                                 };

        //here we can see parameters which is sent to server


        NSLog(@"Sent parameter to server 2 : %@",params);



        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

        manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];


        AFSecurityPolicy* policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];

        [policy setValidatesDomainName:NO];

        [policy setAllowInvalidCertificates:YES];


        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",nil];

        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain",nil];



        [manager POST:Loginurl parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {


            // Here we can see response which is coming from server

            NSLog(@"Response from server 2 :  %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);



        } failure:^(NSURLSessionTask *operation, NSError *error)

         {
             // If Error occur, then this is AlertController Appear

             NSLog(@"Error: %@", error);


             UIAlertController *Erroralert=   [UIAlertController

                                               alertControllerWithTitle:@" Network Connection Failed!!"

                                               message:@"Please try again"

                                               preferredStyle:UIAlertControllerStyleAlert];

             [self presentViewController:Erroralert animated:YES completion:nil];





             UIAlertAction* yesButton = [UIAlertAction

                                         actionWithTitle:@"Ok"

                                         style:UIAlertActionStyleDefault

                                         handler:^(UIAlertAction * action)

                                         {
                                             [self resignFirstResponder];

                                             [Erroralert dismissViewControllerAnimated:YES completion:nil];



                                         }];

             [Erroralert addAction: yesButton];


         }];
    }
Suraj Sukale
  • 1,778
  • 1
  • 12
  • 19
  • Thanks, i'll try your suggestion first :) . I'll let you know later – AlotJai Jan 10 '17 at 07:35
  • Okay, i will waiting for your response @AlotJai – Suraj Sukale Jan 10 '17 at 07:39
  • [self.activityIndicator stopAnimating]; Does not found on object of type view controller – AlotJai Jan 10 '17 at 07:57
  • delete that line and check @AlotJai – Suraj Sukale Jan 10 '17 at 07:59
  • it says that "NSLocalizedDescription=Request failed: unacceptable content-type: text/html}" – AlotJai Jan 10 '17 at 08:05
  • @AlotJai please add 'manager.requestSerializer = [AFHTTPRequestSerializer serializer];' – Suraj Sukale Jan 10 '17 at 08:44
  • @AlotJai please check Output of sent parameter to server . is it in right format? right format means in that format in which your server wants.. plz chk it once and add above line in answer. – Suraj Sukale Jan 10 '17 at 08:49
  • Can you update your answer so i can test it out ? Thanks – AlotJai Jan 10 '17 at 08:52
  • does this code work on your end ? i try to run it . it didnt work . same error appear :( – AlotJai Jan 10 '17 at 09:13
  • Yes @AlotJai it works for me.. Plz check:- 1} the output of NSLog(@"Sent parameter to server 2 : %@",params); is right? 2}You should add App transport security in your info.plist. – Suraj Sukale Jan 10 '17 at 09:22
  • yup . already add NSAppTransportSecurity . I'm not sure why it didn't work . it build successfully – AlotJai Jan 10 '17 at 09:28
  • it build successfully? then where you got error brother @AlotJai – Suraj Sukale Jan 10 '17 at 09:32
  • Nope . . it build successfully . But it has an error when i click on button to request the data . . – AlotJai Jan 11 '17 at 08:49
  • Please check at your server side, that in which format he want data, and what are you going to send server. – Suraj Sukale Jan 11 '17 at 09:24
  • @SurajSukale i was trying to solve this since 5 days and i have been looked into all the POST code available on stackoverflow but i couldnt find my required answer . but after trying your method and way , i got the response from server which is perfect . this code of yours helped me a lot . thanks . – Moxarth Jun 09 '17 at 06:25
  • @Moxarth You are welcome. If its helpful you can vote this answer. May be this is useful to all:) – Suraj Sukale Dec 09 '17 at 03:03
  • yes . i am using this only ever since , though it is a lil bit lengthy code but it is easy to understand the flow . – Moxarth Dec 09 '17 at 06:31