2017-01-09 1 views
0

J'essaye de faire une requête POST en utilisant AFNetworking 3.0. Jusqu'à présent, je n'ai pas trouvé la réponse exacte à ce problème. Soit je ne comprends pas ou une partie du code est obsolète.Demande POST utilisant AFNetworking 3.0 dans xcode 8 (Objective-c)?

erreur est "dataTaskWithRequest est désapprouvée"

Je possède ce deux (2) textfield qui doivent être post dans le serveur Web.

1. email

2. pw

Jusqu'à présent, il n'a pas fonctionné. Le code actuel comme ci-dessous

#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 protected]{@"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 
+0

Qu'est-ce que c'est?: 'Req.timeoutInterval = [[[NSUserDefaults standardUserDefaults] valueForKey: @" email "] longValue];' –

+0

Veuillez regarder la réponse acceptée de [this] (http://stackoverflow.com/questions/ 34561215/afnetworking-3-0-migration-comment-poster-avec-en-têtes-et-http-corps). – Gour

Répondre

0
NSString *URLString = @"http://localhost/test.php";  
    NSDictionary *parameters [email protected]{@"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()); 

      }]; 

télécharger Afnetworking 3.0 dans ce lien https://github.com/AFNetworking/AFNetworking

0

essayer ce code, je suppose qu'il va résoudre votre problème

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

Il suffit de faire comme manière suivante 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]; 


     }]; 
    } 
+0

Merci, je vais d'abord essayer votre suggestion :). Je vous le ferai savoir plus tard – AlotJai

+0

D'accord, j'attendrai votre réponse @AlotJai –

+0

[self.activityIndicator stopAnimating]; Ne trouve pas sur l'objet de type voir contrôleur – AlotJai