Search code examples
iphoneobjective-ciosxmlafnetworking

Get the XML content with AFNetworking library


now i would like use AFNetworking library to get XML content, so I use this code

AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request 
success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) 
{
    XMLParser.delegate = self;
    [XMLParser parse];
} 
failure:nil];
[operation start];

my question is to know if there is any way to get the content of the xml response ( i want to print the xml content with NSLog )

thanks in advance


Solution

  • The raw data from the request is always available in the responseData property of the operation class. Here is how you would show it with NSLog:

    __block AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://legalindexes.indoff.com/sitemap.xml"]] success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
        NSLog(@"Parser: %@", XMLParser);
        NSLog(@"Raw XML Data: %@", [[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding]);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
        NSLog(@"Failure!");
    }];
    
    [operation start];
    

    That said, the standard AFXMLRequestOperation class uses NSXMLParser which is painful to use. If your payload isn't too big and performance isn't an issue, I suggest you use Mattt's new AFKissXMLRequestOperation class which will do the parsing for you and expose a friendlier NSXMLDocument compatible object:

    __block AFKissXMLRequestOperation *operation = [AFKissXMLRequestOperation XMLDocumentRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://legalindexes.indoff.com/sitemap.xml"]] success:^(NSURLRequest *request, NSHTTPURLResponse *response, DDXMLDocument *XMLDocument) {
        NSLog(@"XMLDocument: %@", XMLDocument);
        NSLog(@"Raw XML Data: %@", [[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding]);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, DDXMLDocument *XMLDocument) {
        NSLog(@"Failure!");
    }];
    
    [operation start];