2012-06-12 40 views
4

現在我想用AFNetworking庫獲取XML內容的XML內容,所以我用這個代碼獲取與AFNetworking庫

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

我的問題是要知道是否有任何的方式來獲得的內容XML響應(我要打印的XML內容與NSLog的)

在此先感謝

+3

如果您想接收一個完全實例化的xml文檔,請查看我創建的這個請求操作子類https://github.com/shawnwall/AFGXMLRequestOperation – shawnwall

回答

7

從請求的原始數據總是在操作等級的responseData屬性可用。這裏是你如何與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]; 

這就是說,標準AFXMLRequestOperation類使用NSXMLParser這是痛苦的使用。如果您的有效載荷不太大,性能是不是一個問題,我建議你使用Mattt新AFKissXMLRequestOperation類會做解析,爲您和暴露一個友好NSXMLDocument兼容的對象:

__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]; 
+0

這是更好的答案。 – capikaw

2

我相信AFXMLRequestOperation是SAX操作。也就是說,xml響應沒有被接收到(一直到接收完成)。

您可以通過打印string

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 

或追加字符串到伊娃打印接收到完整的數據並將其打印在parserDidEndDocument

- (void) parserDidEndDocument: (NSXMLParser *)parser 

如果你想測試API看返回。我用這個方法

[[AFHTTPClient sharedClient] postPath:url 
           parameters:nil 
           success:^(AFHTTPRequestOperation *operation , id responseObject) { 
            NSLog(@"responseobject: %@", [responseObject description]); 
            } 
            failure:^(AFHTTPRequestOperation *operation , NSError *error){ 
             NSLog(@"Handle failure for me"); 
            } 
            ]];