You may wish to check whether your NSInputStream
is actually non-nil after this line:
NSInputStream *iStream= [[NSInputStream alloc] initWithURL:url];
Mainly what I see is that you open an NSInputStream
but you never make any HTTP request with it. I think you need to open up a stream pair, and send an HTTP GET request over the NSOutputStream
then listen on the NSInputStream
.
Here's a illustrative code fragment:
#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];
}
}
Usual caveats - this fragment may well be riddled with errors. It isn't intended to be a fully developed solution. For example, I don't actually fetch any data from the stream, etc. The run loop is left running forever, etc. etc.
Finally, this assumes that you really really want to deal with the HTML in this way, for whatever reason.