UIDevice的一些实用的Category

          需要导入SystemConfiguration, CoreFoundation.

头文件

#import 
#import 

@interface UIDevice (Utils)

// 是否是平板
+ (bool)isPad;

// 设备是否有摄像头
+ (bool)hasCamera;

// 获取mac地址
+ (NSString *)getMacAddress;

// 生成GUID
+ (NSString*)generateGUID;

// 判断设备是否越狱
+ (BOOL)isJailbroken;

// 获取系统版本字符串信息
+ (NSString *)getOSVersion;

// 获取系统版本值
+ (float)getOSVersionValue;

+ (NSString *)getModel;

// 获取ip地址
+ (NSString *)getIPAddress;

// 获取可用内存
+ (natural_t)getFreeMemory;

@end

@interface UIDevice (NetWorkConnection)

// 检测当前设备是否联网
+ (BOOL)connectToNetwork;

@end

@interface UIDevice (EmailCapacityAvailable)

// 检测当前设别是否能发送Email
+ (BOOL)canSendMail;

@end

实现文件

#import "UIDevice+Utils.h"
#include  // Per msqr
#include 
#include 
#include 
#import 
#import 
// IP Address
#include 
#include 

// NetWorkConnection
#import 
#include 
#include 
#include 

@implementation  UIDevice(UIMyDevice)

+ (bool)isPad
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        return true;
    }
#endif
    return false;
}

+ (bool)hasCamera
{
  return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

+ (NSString *)getMacAddress
{
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1\n");
        return NULL;
    }
    
    if ((buf = malloc(len)) == NULL) {
        //free(buf); // ?
        printf("Could not allocate memory. error!\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X", 
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    // NSString *outstring = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X", 
    //                       *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    
    return outstring;
}

// 生成GUID
+ (NSString*)generateGUID
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    //NSLog(@"GUID:%@",string);
    return [(NSString *)string autorelease];
}

+ (BOOL)isJailbroken
{
    BOOL jailbroken = NO;
    NSString *cydiaPath = @"/Applications/Cydia.app";
    NSString *aptPath = @"/private/var/lib/apt/";
    if ([[NSFileManager defaultManager] fileExistsAtPath:cydiaPath]) {
        jailbroken = YES;
    }
    if ([[NSFileManager defaultManager] fileExistsAtPath:aptPath]) {
        jailbroken = YES;
    }  
    return jailbroken;  
}


+ (NSString *)getOSVersion
{
    UIDevice *device = [UIDevice currentDevice];
    NSString *os = [NSString stringWithFormat:@"%@ %@",[device systemName],[device systemVersion]];
    //NSLog(@"Current Client System:%@",os);
    return os;
}

// 获取系统版本值
+ (float)getOSVersionValue
{
    UIDevice *device = [UIDevice currentDevice];
    return [[device systemVersion] floatValue];
}

+ (NSString *)getModel
{
    UIDevice *device = [UIDevice currentDevice];
    NSString *model = device.model;
    //NSLog(@"Current client model:%@",model);
    return model;
}

+ (NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0)
    {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL)
        {
            if(temp_addr->ifa_addr->sa_family == AF_INET)
            {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
                {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    
    return address;
}


// 获取当前app可用的剩余内存
+ (natural_t)getFreeMemory
{
    mach_port_t host_port;
    mach_msg_type_number_t host_size;
    vm_size_t pagesize;
    host_port = mach_host_self();
    host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
    host_page_size(host_port, &pagesize);
    vm_statistics_data_t vm_stat;
    
    if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {
        NSLog(@"Failed to fetch vm statistics");
        return 0;
    }
    
    /* Stats in bytes */
    natural_t mem_free = vm_stat.free_count * pagesize;
    return mem_free;
}


@end


@implementation UIDevice (NetWorkConnection)

+ (BOOL)connectToNetwork
{
	struct sockaddr_in zeroAddress;
	
	bzero(&zeroAddress, sizeof(zeroAddress));
	zeroAddress.sin_len = sizeof(zeroAddress);
	zeroAddress.sin_family = AF_INET;
	
	SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*)&zeroAddress);
	
	SCNetworkReachabilityFlags flags;
	BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
	
	if (!didRetrieveFlags)
	{
		return FALSE;
	}
	
	BOOL isReachable = flags & kSCNetworkFlagsReachable;
	BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
	return (isReachable && !needsConnection)?TRUE:FALSE;
}

@end

@implementation UIDevice (EmailCapacityAvailable)

+ (BOOL)canSendMail
{
	Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
	if (mailClass != nil)
	{
		// We must always check whether the current device is configured for sending emails
		if ([mailClass canSendMail])
		{
			return TRUE;
		}
	}
	
	return FALSE;
}

@end


你可能感兴趣的:(iOS)