Handling errors in CFReadStream - Obj-C

103 views Asked by At

How do I handle errors in a stream? If the user is connected to the wrong network I want to handle that. Thanks!

Code:

- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"IP HERE", 7777, &readStream, &writeStream);
_inputStream = (NSInputStream *)CFBridgingRelease(readStream);
_outputStream = (NSOutputStream *)CFBridgingRelease(writeStream);

[_inputStream setDelegate:self];
[_outputStream setDelegate:self];

[_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[_inputStream open];
[_outputStream open];
}
1

There are 1 answers

0
Yomo On BEST ANSWER

I figured out a solution that worked in my case. This code will print out the current network's BSSID in the console, and I simply check if the BSSID matches the one for my preferred network with an if-statement:

#import <SystemConfiguration/CaptiveNetwork.h>

//Checks which network the user is connected to.
CFArrayRef myArray = CNCopySupportedInterfaces();
CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
NSLog(@"Connected at: %@", myDict);
NSDictionary *myDictionary = (__bridge_transfer NSDictionary*)myDict;
NSString * BSSID = [myDictionary objectForKey:@"BSSID"];
NSLog(@"BSSID is: %@", BSSID);

//Handling wrong/correct BSSID.
if (![BSSID isEqualToString:@"PREFERRED BSSID HERE"]) {
    //Handle error however you want.
}
else {
    //If correct BSSID, handle that here however you want.
}
}