我想读取来自Web服务的响应。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFXMLParserResponseSerializer new];
[manager GET:@"http://openapi.aibang.com/search?app_key=f41c8afccc586de03a99c86097e98ccb&city=%E5%8C%97%E4%BA%AC&q=%E9%A4%90%E9%A6%86" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

但是我只从Xcode日志中获得了<NSXMLParser: 0x15d85490>。这不是正确的xml响应。

最佳答案

EN:因为responseObjectNSXMLParser实例,所以您不能将其视为字符串!
您必须实现NSXMLParserDelegate来处理xml解析器的进度!

CN:responseObject返回的是NSXMLParser实例,您必须实现NSXMLParserDelegate协议才能处理该XML类型!骚年! :-)

解决方案1:使用NSXMLParser进行解析

[manager GET:@"http://openapi.aibang.com/search?app_key=f41c8afccc586de03a99c86097e98ccb&city=%E5%8C%97%E4%BA%AC&q=%E9%A4%90%E9%A6%86" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSXMLParser *XMLParser = (NSXMLParser *)responseObject;
    [XMLParser setShouldProcessNamespaces:YES];
    XMLParser.delegate = self;
    [XMLParser parse];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

解决方案2:使用GDataXML进行解析(容易得多)
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"http://openapi.aibang.com/search?app_key=f41c8afccc586de03a99c86097e98ccb&city=%E5%8C%97%E4%BA%AC&q=%E9%A4%90%E9%A6%86" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
   GDataXMLDocument *doc = [[GDataXMLDocument alloc]initWithData:responseObject encoding:0 error:nil];
   NSLog(@"%@",doc.rootElement);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

关于ios - AFNetworking 2.0无法解析xml,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27288953/

10-10 03:52