您的位置:首页 > 移动开发 > Objective-C

Connect to specified wifi router in Macintosh, by Objective C

2015-04-02 13:14 218 查看
     Similar to
the other article of mine: In here, I post the code which could connect to target wifi router. The Xcode project be set as :
Base SDK is 10.7, and  OSX deployment SDK as 10.5. The code depends on the frame work CoreWLAN.framework of 10.7 (it exists in /Developer/SDKs/MacOSX10.7.sdk/System/Library/Frameworks by default , if you have installed 10.7 SDK), you should
add it to your Xcode project. The could running in OS X 10.8 and 10.9  without any wrong(both 32 and 64 bit).

    If you do not install 10.7 SDK, to set the environment, it is necessary to download  OS X 10.7 SDK. you could download it from
here ( need apple id). Refer to

the article in stack overflow, SDKs of OS X are bundled with  each version of Xcode (10.5 -> 3.1, 10.6 ->3.2, 10.7 ->4.3, 10.8 -> 5.1, 10.9 -> 6.0, respectively). In here, you should download Xcode 4.3, extract the 10.7 SDK to your computer.

The code is in objective-C, but the function call is C-style, for C/C++ calling compatible.

#import <CoreWLAN/CoreWLAN.h>

int ConnectToTargetWifiSSID(char *pSSIDName, char *pPassword)
{
@autoreleasepool {
if(NULL == pSSIDName)
return -1;

NSString *ssidName = [ [NSString alloc] initWithUTF8String : pSSIDName ];
//NSLog(@"%@", ssidName);

CWInterface *currentInterface = [CWInterface interface];

if( [ssidName isEqualToString: [currentInterface ssid]])
{
printf("current is %s\n", pSSIDName);
return 1;
}/*if*/

if( NO== currentInterface.powerOn)
{
printf("wireless card has been turn off\n");
return -1;
}/*if */

NSArray *networks = [[currentInterface scanForNetworksWithName:nil error:nil] allObjects];

if(0 == [networks count])
{
printf("no available wifi ap\n");
return -2;
}/*if */

printf("available wifi ssid name:\n");
for(int i = 0; i< [networks count]; i++){
printf("%s \n", [[[networks objectAtIndex:i] ssid] cStringUsingEncoding:NSUTF8StringEncoding]);
}/*for*/

int iii;
iii = -1;

for(int i = 0; i< [networks count]; i++){
if([ ssidName isEqualToString: [[networks objectAtIndex:i] ssid] ])
{
iii = i;
break;
}/*if*/
}/*for*/

if(-1 == iii)
{
printf("no available wifi ssid name marches %s\n", pSSIDName);
return -3;
}/*if*/

NSString *password;

if(NULL == pPassword)
password = [ [NSString alloc] initWithFormat:@"%@",@"    "];
else
password = [ [NSString alloc] initWithUTF8String : pPassword];

//NSLog(@"%@", password);

CWNetwork * network = [networks objectAtIndex:iii];

BOOL isSuccess;

isSuccess = [currentInterface associateToNetwork:network password:password error:nil];

if(NO == isSuccess)
return -6;

}/*@autoreleasepool*/

return 0;
}/*ConnectToTargetWifiSSID*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  macintosh objective-c wifi
相关文章推荐