2012-11-19 3 views
0

그래서 저는 자바에서 웹 사이트의 렌더링 된 HTML 소스 코드를 읽는 데 많은 경험을했습니다. 그러나 Objective-C에서 정확히 동일한 작업을 수행하는 방법을 철저히 조사하고 작동해야하는 솔루션을 제시 할 수는 있었지만 실제로는 그렇지 않습니다. 아이디어는 각 행을 읽으려는 것입니다. 예를 들면 "view-source : www.apple.com", 그 행의 결과를 한 줄씩 읽길 원합니다.Objective-C에서 렌더링 된 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"); 

이 실행되고 잘 컴파일,하지만 결과는 내가 연구의 AA 많은 일을 한 또 항상 0이고 내가 안 : 나는이 내가 가지고있는 어떤 HTML 파서 등 을 원하지 않는 왜 결과가 0인지 이해하십시오. 어떤 도움을 주시면 감사하겠습니다.

+0

이 다른 솔루션은 작동했습니다 ... NSString * s = [NSString stringWithFormat : @ "http://www.apple.com"]; NSURL * url = [NSURL URLWithString : s]; \t \t NSData * data = [NSData dataWithContentsOfURL : url]; \t는 NSString가 newStr * = [있는 NSString ALLOC] initWithData : 데이터 \t \t \t \t \t \t \t \t \t \t \t 인코딩 : NSUTF8StringEncoding]; \t NSLog (@ "data : % @", newStr); 비록 비효율적 인 것처럼 페이지 단위로 줄을 읽었을 지 모르지만 나는 받아 들일 것입니다. – Jessicardo

답변

0

...하지만

NSString *s = [NSString stringWithFormat:@"http://www.apple.com"]; 
NSURL *url = [NSURL URLWithString:s]; 


NSData *data = [NSData dataWithContentsOfURL:url]; 
NSString* newStr = [[NSString alloc] initWithData:data 
             encoding:NSUTF8StringEncoding]; 
NSArray *arr= [newStr componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; 

, 나는 오히려이이 보인다 라인으로 페이지 라인을 읽을 것이다 비효율적 인 -하지만 난 더 나은 찾을 수있을 때까지 나는 지금이 함께 정착 것 대답.

0

당신은 당신의 NSInputStream가 nil이 아닌이 줄 끝에서 사실 여부를 확인하실 수 있습니다 :

NSInputStream *iStream= [[NSInputStream alloc] initWithURL:url]; 

주로 내가 보는 것은 당신이 NSInputStream을 열 수 있지만, 당신이 어떤 HTTP 요청을하지 않을 것입니다. 스트림 쌍을 열어야하고 NSOutputStream을 통해 HTTP GET 요청을 보내고 NSInputStream에서 수신 대기해야한다고 생각합니다. -이 조각은 물론 오류로 가득 할 수있다

#import <Foundation/Foundation.h> 

@interface CCFStreamReader : NSObject <NSStreamDelegate> 
- (void)readStream; 
@end 

@implementation CCFStreamReader { 
    NSInputStream *_inputStream; 
    NSOutputStream *_outputStream; 
} 
- (void)readStream { 
    NSURL *url = [NSURL URLWithString:@"http://www.apple.com"]; 
    CFReadStreamRef readStream; 
    CFWriteStreamRef writeStream; 
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)[url host], 80, &readStream, &writeStream); 

    _inputStream = (__bridge_transfer NSInputStream *)readStream; 
    _outputStream = (__bridge_transfer NSOutputStream *)writeStream; 
    [_inputStream setDelegate:self]; 
    [_outputStream setDelegate:self]; 
    [_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
    [_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
    [_inputStream open]; 
    [_outputStream open]; 
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]]; 
    NSLog(@"input stream = %@",_inputStream); 
    printf("read something"); 
} 

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)streamEvent { 
    printf("stream event: %d\n",(int)streamEvent); 
    switch(streamEvent) { 
     case NSStreamEventHasSpaceAvailable: 
     { 
      if (aStream == _outputStream) { 
       NSString *str = [NSString stringWithFormat: 
            @"GET/HTTP/1.0\r\n\r\n"]; 
       const uint8_t *rawstring = (const uint8_t *)[str UTF8String]; 
       [_outputStream write:rawstring maxLength:str.length]; 
       [_outputStream close]; 
      } 
      break; 
     } 
     case NSStreamEventHasBytesAvailable: { 
      printf("Bytes available\n"); 
     } 
    } 

} 

@end 

int main(int argc, char *argv[]) { 

    @autoreleasepool { 
     CCFStreamReader *reader = [CCFStreamReader new]; 
     [reader readStream]; 
    } 
} 

일반적인주의 사항 :

는 여기에 설명을 코드 조각입니다. 완전히 개발 된 솔루션이되는 것은 아닙니다. 예를 들어 실제로 스트림에서 데이터를 가져 오지는 않습니다. 실행 루프는 영원히 계속 실행됩니다.

마지막으로, 여기서는 HTML을이 방식으로 처리하려고한다고 가정합니다 , 이유가 무엇이든지. 이 다른 솔루션은 일