我正在处理的基本问题是使用NSStream
类来解析传入的增量 XML 数据。数据从来都不是一个完整的 XML 文档,但我想根据套接字可以读取的数量以增量块的形式接收和处理它。
查看文档NSXMLParser
,似乎initWithStream:
初始化 a 的方法NSXMLParser
将是我的问题的完美解决方案。我可以用 a 初始化解析器,NSInputStream
然后每当我通过我的套接字接收数据时调用该parse
方法,这又应该调用委托。NSXMLParser
NSXMLParser
但是,我没有看到任何被调用的委托,我看到的唯一被调用的方法是流委托stream:handleEvent:
。Apple 或其他开发人员似乎几乎没有此 API 的示例。关于我做错了什么或如何initWithStream:
正确使用的任何想法?
内容解析器.h
@interface ContentParser : NSObject <NSStreamDelegate,
NSXMLParserDelegate>
{
NSInputStream *inputStream;
NSOutputStream *outputStream;
NSMutableData *receivedData;
NSXMLParser *xmlParser;
}
- (void)initStream;
内容解析器.m
@implementation ContentParser
- (void)initStream
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
(CFStringRef)@"<hostname>",
<port>,
&readStream,
&writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
inputStream.delegate = self;
outputStream.delegate = self;
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
xmlParser = [[NSXMLParser alloc] initWithStream:inputStream];
[xmlParser setDelegate:self];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
NSLog(@"didStartElement: %@, attributeDict: %@", elementName, attributeDict);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(@"foundCharacters: %@", string);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
NSLog(@"didEndElement: %@", elementName);
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
NSLog(@"Error %ld, Description: %@, Line: %ld, Column: %ld",
[parseError code], [[parser parserError] localizedDescription],
[parser lineNumber], [parser columnNumber]);
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
switch (eventCode) {
case NSStreamEventHasBytesAvailable:
{
if (stream == inputStream) {
NSInputStream *is = (NSInputStream *)stream;
if (receivedData == nil) {
receivedData = [[NSMutableData alloc] init];
}
uint8_t buf[1024];
NSInteger bytesRead = [is read:buf maxLength:1024];
if (bytesRead == -1) {
NSLog(@"Network read error");
} else if (bytesRead == 0) {
NSLog(@"No buffer received");
} else {
[receivedData appendBytes:buf length:bytesRead];
BOOL parserResult = [xmlParser parse];
if (parserResult == NO) {
NSLog(@"Unable to parse XML");
}
}
}
break;
}
default:
break;
}
}
@end