Bear with me please, I’m a new programmer. (things I say might not make sense)
I’m trying to create an inputStream and outPut stream so that I can write to it using JSON objects elsewhere in the class…
I wanted to know if I’m doing it right. Currently, I’m opening the streams in -(id)init{}
-(id)init{
_isNetworkAvailable = FALSE;
//kCFAllocatorDefault is the same thing as Null
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)requestURL, port, &readStream, &writeStream);
NSInputStream *inputStream = (__bridge NSInputStream *)readStream;
NSOutputStream *outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
//There should really be some checking going on here, but we're going to forget it for now
//Call some checking method
_isNetworkAvailable = TRUE;
return self;
}
My question is: is this the right way to handle something like this? Should I declare NSInputStream and NSOutputStream elsewhere?
Why do I have to cast my CFStreams as NSStreams?
With some testing, this was the proper way of creating streams.
CFStreams are cast to NSStreams because NSStreams are obj-c native and provide more options and flexibility with use. NSStream is actually based on CFStream (which is a wrapper on BSD sockets).
This code should always be run asynchronously, as far as I can tell, or you’ll see some hanging during runtime.