我有一个过时的应用程序,用于下载 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
with 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 缺少标签分隔符<>
。我想我错过了获取 xml 数据的方法。
PS:请注意,我在NSMutableString
对象中获取 xml 很重要。
@费米
我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"];
wo 由于NSURLConnection
没有调用委托方法,我该如何管理失败等?谢谢。