2017-01-09 71 views
0

我正在嘗試使用AFNetworking 3.0 POST請求。在xcode 8(Objective-c)中使用AFNetworking 3.0的POST請求?

到目前爲止,我沒有找到這個問題的確切答案。要麼我不明白,或者某些代碼已被棄用。

錯誤是「dataTaskWithRequest已經過時」

我有這個兩(2)文本框需要被後到Web服務器。

1.電子郵件

2. PW

到目前爲止,沒有工作。當前的代碼如下

#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

這是什麼?:''req.timeoutInterval = [[[NSUserDefaults standardUserDefaults] valueForKey:@「email」] longValue];' –

+0

請看看[this]的接受的答案(http://stackoverflow.com/questions/ 34561215/afnetworking-3-0-遷移如何對後具有報頭和-HTTP-體)。 – Gour

回答

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()); 

      }]; 

下載在這個環節https://github.com/AFNetworking/AFNetworking

0

Afnetworking 3.0試試這個代碼,我想這將解決您的問題

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

簡單地做像下面的方式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

謝謝,我會先試試你的建議:)。我會讓你知道後 – AlotJai

+0

好吧,我會等待你的回覆@AlotJai –

+0

[self.activityIndi​​cator stopAnimating];沒有找到類型視圖控制器 – AlotJai