你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS編程技術 >> iOS下的WiFi開發熱點獲取等

iOS下的WiFi開發熱點獲取等

編輯:IOS編程技術

  iOS下Wi-Fi開發需要添加依賴庫SystemConfiguration.framework,在需要使用Wi-Fi信息的控制器下引入頭文件#import <SystemConfiguration/CaptiveNetwork.h>

  1,Wi-Fi熱點獲取

+(NSString *) currentWifiSSID
{
#if TARGET_OS_SIMULATOR
    return @"(simulator)";
#else
    NSArray *ifs = (__bridge id)CNCopySupportedInterfaces();

    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info && [info count]) {
            break;
        }
    }
    NSDictionary *dctySSID = (NSDictionary *)info;
    NSString *ssid = [dctySSID objectForKey:@"SSID"] ;

    return ssid;
#endif
}

  2,取得本機Wi-Fi的IP地址

#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>
#import <dlfcn.h>

+(NSString *) localWiFiIPAddress
{
    BOOL success;
    struct ifaddrs * addrs;
    const struct ifaddrs * cursor;

    success = getifaddrs(&addrs) == 0;
    if (success) {
        cursor = addrs;
        while (cursor != NULL) {
            // the second test keeps from picking up the loopback address
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
            {
                NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
                if ([name isEqualToString:@"en0"])  // Wi-Fi adapter
                    return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return nil;
}

  3,獲取當前Wi-Fi的名稱

- (void)GetWifiName{

NSString *wifiName = @"Not Found";

CFArrayRef myArray = CNCopySupportedInterfaces();

if (myArray != nil) {

CFDictionaryRef myDict =CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));

if (myDict != nil) {

NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);

wifiName = [dict valueForKey:@"SSID"];

}

NSLog(@"wifiName:%@", wifiName);

}

  注意:需要真機才能測試!模擬器下返回空。

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved