I cannot initialize a NSInputStream

你说的曾经没有我的故事 提交于 2019-12-06 12:08:33

Thanks everyone, i found it.

The thing is, my question already had all the clues i would have needed, because, like i wrote, NSStream`s -initWithURL: will

Create and return an initialized NSInputStream object that reads data from
the file at a given URL.

What I didn't see is that this is only true for local sources. If you want a remote host, (i had a wireless network connection) you need to use something else, because, and i quote the docs again here:

The NSStream class does not support connecting to a remote host on iOS.

Well, for what its worth, you need to create a CFReadStreamRef and a CFWriteStreamRef, and then use the magic function CFStreamCreatePairWithSocketToHost to connect them to your host. After that, you can cast them to NSInputStream and NSOutputStream respectively, and they will work as intended. Heres a code example from the docs:

    CFReadStreamRef readStream;

    CFWriteStreamRef writeStream;

    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)[website host], 80, &readStream, &writeStream);



    NSInputStream *inputStream = (__bridge_transfer NSInputStream *)readStream;

    NSOutputStream *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];

Hope this helps someone at some point.

@leparlon:

Im upvoting your answer, since you were definitly on the right track, suggesting the use of initWithData.

If you are using ARC, that might fix it:

EDIT: Downloading it into a NSData first might fix it

NSInputStream *tempStream;
NSData *tempData = [NSData dataWithContentsOfURL:@"Your Url"]; 
tempStream = [[NSInputStream alloc] initWithData:tempData]; 
liveViewStream = tempStream; 
DLog(@"%@", liveViewStream);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!