AnshaD AnshaD - 4 months ago 207
iOS Question

Afnetworking 3.0 Migration : How to post with xml post body

I am trying to POST some data to the server with body formatted as XML, everything works well with

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


Now in Afnetworking 3.0 they changed AFHTTPRequestOperation to AFHTTPSessionManager any way to do post xml data with AFHTTPSessionManager

Answer

You can use AFURLSessionManager class for this use. For that, create a AFURLSessionManager instance then create NSURLSessionDataTask from the manager with your NSURLRequest . Use that task to post your data Eg code:

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

Update If you are using AFXMLParserResponseSerializer as response serializer, then Add this code to start xml parsing

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

And implement NSXMLParserDelegate methods.

You can find a nice tutorial for parsing xml here - XML Parsing with NSXMLParser

Comments