【问题标题】:POST request using AFNetworking 3.0 in xcode 8 (Objective-c)?在 xcode 8 (Objective-c) 中使用 AFNetworking 3.0 发布请求?
【发布时间】:2017-01-09 03:53:01
【问题描述】:

我正在尝试使用 AFNetworking 3.0 发布请求。

到目前为止,我还没有找到这个问题的确切答案。要么我不明白,要么某些代码已被弃用。

错误是 “dataTaskWithRequest 已弃用”

我有这 两 (2) 个需要发布到网络服务器的文本字段。

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" : @"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

【问题讨论】:

  • 这是什么?:req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"email"] longValue];
  • 请看this接受的答案。

标签: objective-c xcode8 afnetworking-3


【解决方案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());

          }];

在这个链接https://github.com/AFNetworking/AFNetworking下载Afnetworking 3.0

【讨论】:

    【解决方案2】:

    试试这个代码,我想它会解决你的问题

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

    【讨论】:

      【解决方案3】:

      只需在 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];
      
      
               }];
          }
      

      【讨论】:

      • 谢谢,我会先试试你的建议 :) 。稍后我会通知你
      • 好的,我会等你的回复@AlotJai
      • [self.activityIndi​​cator stopAnimating];在视图控制器类型的对象上找不到
      • 删除该行并检查@AlotJai
      • 它说“NSLocalizedDescription=Request failed: unacceptable content-type: text/html}”
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多