Afnetworking 3.0迁移:如何使用xml post body发布

时间:2016-01-14 05:56:44

标签: ios afnetworking afnetworking-3

我正在尝试将一些数据发布到服务器,主体格式为XML,一切都适用于

request.HTTPBody = [self.body dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"POST";
 [request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

现在在Afnetworking 3.0中他们将AFHTTPRequestOperation更改为AFHTTPSessionManager以任何方式使用AFHTTPSessionManager发布xml数据

1 个答案:

答案 0 :(得分:6)

您可以使用AFURLSessionManager类来实现此用途。为此,创建一个AFURLSessionManager实例,然后使用NSURLRequest从经理创建NSURLSessionDataTask。使用该任务发布您的数据 例如代码:

NSMutableURLRequest *request = ....;
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes =  [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/xml"];
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSString *fetchedXML = [[NSString alloc] initWithData:(NSData *)responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"Response string: %@",fetchedXML);
 }];
[task resume];

<强>更新 如果您使用AFXMLParserResponseSerializer作为响应序列化程序,那么 添加此代码以启动xml解析

NSXMLParser *xmlparser = responseObject;
[xmlparser setDelegate:self];
[xmlparser parse];

实施NSXMLParserDelegate方法。

你可以在这里找到一个很好的教程来解析xml - XML Parsing with NSXMLParser