【发布时间】:2012-11-19 18:48:06
【问题描述】:
因此,我在阅读 Java 网站的渲染 html 源代码方面拥有丰富的经验。然而,我已经彻底研究了如何在 Objective-C 中做同样的事情,并且已经能够提出一个应该有效的解决方案,但它没有。 这个想法是我想阅读每一行,例如:“view-source:www.apple.com”,我想逐行阅读该页面的结果。我不想要任何 Html 解析器等。 这就是我所拥有的:
NSString *s = [NSString stringWithFormat:@"http://www.apple.com"];
NSURL *url = [NSURL URLWithString:s];
NSInputStream *iStream= [[NSInputStream alloc] initWithURL:url];
[iStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[iStream open];
NSLog(@"stream successfully opened");
NSInteger result;
uint8_t buffer[1024];
while((result = [iStream read:buffer maxLength:1024]) != 0) {
if(result > 0) {
NSLog(@"Buffer is %@",buffer);
// buffer contains result bytes of data to be handled
} else {
NSLog(@"ERROR: %@",buffer);
// The stream had an error. You can get an NSError object using [iStream streamError]
}
NSLog(@"end of while loop: %@",buffer);
}
// Either the stream ran out of data or there was an error
NSLog(@"Either the stream ran out of data or there was an error");
这可以正常运行和编译,但结果始终为 0。我再次进行了大量研究,但我不明白为什么结果为 0。感谢任何帮助。
【问题讨论】:
-
这个其他解决方案有效... NSString s = [NSString stringWithFormat:@"apple.com"]; NSURL *url = [NSURL URLWithString:s]; NSData *data = [NSData dataWithContentsOfURL: url]; NSString newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"data : %@",newStr); 不过,我宁愿像这样逐行阅读页面似乎效率低下-但我会接受的。
标签: iphone objective-c xcode screen-scraping nsinputstream