处理CFReadStream中的错误 - Obj-C

问题描述:

如何处理流中的错误?如果用户连接到错误的网络,我想处理该问题。谢谢!处理CFReadStream中的错误 - Obj-C

代码:

- (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]; 
} 

我想通了,在我的情况下工作的解决方案。此代码将在控制台中打印出当前网络的BSSID,我只需使用if语句检查BSSID是否与我的首选网络匹配:

#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. 
} 
}