我有一个过时的应用程序,用于下载XML文档并在iPhone应用程序上解析它,我为此目的使用了NSURLConnection
:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//NSLog(@"Response :%@",response);
responseData = [[NSMutableString alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *str = [[NSString alloc] initWithData:data
encoding:NSASCIIStringEncoding];
[responseData appendString:str];
[str release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"DATA : %@",responseData);
if (responseData != nil) {
[self startParsing:responseData];//Parse the data
[responseData release];
}
}
自从NSXMLParserDelegate
移至AFXMLRequestOperation
后,我无法找到正确获取xml数据的方法:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
[responseData appendString:elementName];
[responseData appendString:namespaceURI];
[responseData appendString:qName];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
[responseData appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
[responseData appendString:elementName];
[responseData appendString:namespaceURI];
[responseData appendString:qName];
}
-(void) parserDidEndDocument:(NSXMLParser *)parser{
[SVProgressHUD showSuccessWithStatus:@"Downloading completed"];
NSLog(@"DATA : %@",responseData);//not properly appended, tags delimeters are missing
if (responseData != nil) {
[self startParsing:responseData];
[responseData release];
}
}
如何在responseData
可变字符串中附加从服务器收到的所有数据?我在完成下载后调试了收到的数据,并且xml缺少标记delimeters <>
。我想我错过了获取xml数据的方法。
P.S:请注意我在NSMutableString
对象中获取xml很重要。
@Fermi
我按照你的建议使用了AFURLConnectionOperation
,它可以正常工作,但我注意到我的接收数据没有被委托方法捕获,而是我可以在完成块中获取数据:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:API_URL]];
AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request];
operation.completionBlock = ^{
NSLog(@"Complete: %@",operation.responseString);//responseString is my data
};
[operation start];
[SVProgressHUD showWithStatus:@"Downloading files"];
由于没有调用NSURLConnection
委托方法,我如何管理失败等?感谢名单。
答案 0 :(得分:1)
AFXMLRequestOperation
明确用于返回NSXMLDocument
实例,而不是原始XML字符串。
如果您希望XML字符串使用AFURLConnectionOperation
并使用与NSMutableString
相同的方式构建NSURLConnection
。