ios获取设备信息

1、获取设备的基本信息

UIDevice *device = [[UIDevice alloc] int];  
NSString *name = device.name;       //获取设备所有者的名称  
NSString *model = device.name;      //获取设备的类别  
NSString *type = device.localizedModel; //获取本地化版本  
NSString *systemName = device.systemName;   //获取当前运行的系统  
NSString *systemVersion = device.systemVersion;//获取当前系统的版本  
NSString *identifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; //获取设备的唯一标识

2、获取当前屏幕的分辨率信息

CGRect rect = [[UIScreen mainScreen] bounds];  
CGFloat scale = [[UIScreen mainScreen].scale];  
CGFloat width = rect.size.width * scale;  
CGFloat height = rect.size.height * scale;  

3、获取运营商信息

- (void)getCarrierInfo {
    // 获取运营商信息
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = info.subscriberCellularProvider;
    NSLog(@"carrier:%@", [carrier description]);
    
    // 如果运营商变化将更新运营商输出
    info.subscriberCellularProviderDidUpdateNotifier = ^(CTCarrier *carrier) {
        NSLog(@"carrier:%@", [carrier description]);
    };
    
    // 输出手机的数据业务信息
    NSLog(@"Radio Access Technology:%@", info.currentRadioAccessTechnology);
    
    
    // 监控通话信息
    CTCallCenter *center = [[CTCallCenter alloc] init];
    center_ = center;
    center.callEventHandler = ^(CTCall *call) {
        NSSet *curCalls = center_.currentCalls;
        NSLog(@"current calls:%@", curCalls);
        NSLog(@"call:%@", [call description]);
    };
}
/**
 *  运营商网络状态
 *
 *  @return 网络状态
 */
- (NSString *) carrierStatus
{
    CTTelephonyNetworkInfo *info=[CTTelephonyNetworkInfo new];
    NSString *status=info.currentRadioAccessTechnology;
    
    if (status == nil || [status length] <= 0) {
        return @"UnKnow";
    }
    
    if([status isEqualToString:CTRadioAccessTechnologyCDMA1x]||[status isEqualToString:CTRadioAccessTechnologyGPRS])
        return @"2G";
    else if([status isEqualToString:CTRadioAccessTechnologyEdge])
        return @"Edge";
    else if([status isEqualToString:CTRadioAccessTechnologyLTE])
        return @"4G";
    else
        return @"3G";
}

4、流量统计

/**
 流量统计
 
 @return 接收和发送的流量
 */
+ (NSString *)getNetWorkCounter
{
    BOOL   success;
    struct ifaddrs *addrs;
    const struct ifaddrs *cursor;
    const struct if_data *networkStatisc;
    
    int WiFiSent = 0;
    int WiFiReceived = 0;
    int WWANSent = 0;
    int WWANReceived = 0;
    
    NSString *name=[[NSString alloc]init];
    
    success = getifaddrs(&addrs) == 0;
    if (success)
    {
        cursor = addrs;
        while (cursor != NULL)
        {
            
            name=[NSString stringWithFormat:@"%s",cursor->ifa_name];
//            NSLog(@"ifa_name %s == %@n", cursor->ifa_name,name);
            // names of interfaces: en0 is WiFi ,pdp_ip0 is WWAN
            
            if (cursor->ifa_addr->sa_family == AF_LINK)
            {
                if ([name hasPrefix:@"en"])
                {
                    networkStatisc = (const struct if_data *) cursor->ifa_data;
                    WiFiSent+=networkStatisc->ifi_obytes;
                    WiFiReceived+=networkStatisc->ifi_ibytes;
                    // NSLog(@"WiFiSent %d ==%d",WiFiSent,networkStatisc->ifi_obytes);
                    //NSLog(@"WiFiReceived %d ==%d",WiFiReceived,networkStatisc->ifi_ibytes);
                }
                
                if ([name hasPrefix:@"pdp_ip"])
                {
                    networkStatisc = (const struct if_data *) cursor->ifa_data;
                    WWANSent+=networkStatisc->ifi_obytes;
                    WWANReceived+=networkStatisc->ifi_ibytes;
                    // NSLog(@"WWANSent %d ==%d",WWANSent,networkStatisc->ifi_obytes);
                    //NSLog(@"WWANReceived %d ==%d",WWANReceived,networkStatisc->ifi_ibytes);
                    
                }
            }
            
            cursor = cursor->ifa_next;
        }
        
        freeifaddrs(addrs);
    }
    NSLog(@"wifi发送:%.2f   wifi收到:%.2f    2g/3g/4g发送:%.2f    2g/3g/4g收到:%.2f ",WiFiSent/1024.0/1024.0,WiFiReceived/1024.0/1024.0,WWANSent/1024.0/1024.0,WWANReceived/1024.0/1024.0);
    NSString *liuliangStr = [NSString stringWithFormat:@"wifi发送:%.2f   wifi收到:%.2f    2g/3g/4g发送:%.2f    2g/3g/4g收到:%.2f ",WiFiSent/1024.0/1024.0,WiFiReceived/1024.0/1024.0,WWANSent/1024.0/1024.0,WWANReceived/1024.0/1024.0];
    
//    return [NSArray arrayWithObjects:[NSNumber numberWithInt:WiFiSent], [NSNumber numberWithInt:WiFiReceived],[NSNumber numberWithInt:WWANSent],[NSNumber numberWithInt:WWANReceived], nil];
    return liuliangStr;
}

5、电池相关信息

//获取电池当前的状态,共有4种状态  
-(NSString*) getBatteryState {    
    UIDevice *device = [UIDevice currentDevice];    
    if (device.batteryState == UIDeviceBatteryStateUnknown) {    
        return @"UnKnow";    
    }else if (device.batteryState == UIDeviceBatteryStateUnplugged){    
        return @"Unplugged";    
    }else if (device.batteryState == UIDeviceBatteryStateCharging){    
        return @"Charging";    
    }else if (device.batteryState == UIDeviceBatteryStateFull){    
        return @"Full";    
    }  
    return nil;   
}   
//获取电量的等级,0.00~1.00  
-(float) getBatteryLevel {    
    return [UIDevice currentDevice].batteryLevel;  
}   
  
-(void) getBatteryInfo  
{  
    NSString *state = getBatteryState();  
    float level = getBatteryLevel()*100.0;  
    //yourControlFunc(state, level);  //写自己要实现的获取电量信息后怎么处理  
}  
  
//打开对电量和电池状态的监控,类似定时器的功能  
-(void) didLoad  
{  
    [[UIDevice currentDevice] setBatteryMonitoringEnable:YES];  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getBatteryInfo:) name:UIDeviceBatteryStateDidChangeNotification object:nil];  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getBatteryInfo:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];  
    [NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(getBatteryInfo:) userInfo:nil repeats:YES];  
} 

6、在app中打开一个网页

 NSString *url = @"www.apple.com"  
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];  

7、在app中打开另一个app
1)启动内置的应用,一般的电话,浏览器,短信和
邮件可以直接调用并添加参数

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://123456"]];  
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://devprograms@apple.com"]];  
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://1008611"]];

2)打开自己开发的app,这种情况则要为将要打开的app注册一个URL协议。
具体方法是在项目的文件info.plist中添加:
<key>URL types</key>
<dict>
<key>URL identifier</key>
<string>@"com.apple.developer"<string/> //可以是任何值,但建议用“反域名”
<key>URL Schemes</key>
<string>@"testDemo"<string/> //输入你的URL协议名,例如“testHello://” 应写做“testHello”,可以在这里加入多个协议
</dict>

NSString *url = @"URL Schemes的路径"  
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];    

8、获取用户地理位置

/**
 获取用户的地理位置
 */
-(void)getUserLocation
{
    if ([CLLocationManager locationServicesEnabled]) {
        CLLocationManager *manager = [[CLLocationManager alloc]init];
        [manager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
        manager.delegate = self;
        [manager startUpdatingLocation];
    }
}

#pragma mark - CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    NSLog(@"%@", locations);
    [manager stopUpdatingLocation];
        CLLocation *newLocation = [locations lastObject];
        CLLocationCoordinate2D newCoordinate = newLocation.coordinate;
        NSLog(@"经度:%f,纬度:%f",newCoordinate.longitude,newCoordinate.latitude);
    
    
    //-----位置反编码---
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:newLocation
                   completionHandler:^(NSArray *placemarks, NSError *error){
                       
                       for (CLPlacemark *place in placemarks) {
                           NSLog(@"name,%@",place.name);                       // 位置名
                           NSLog(@"thoroughfare,%@",place.thoroughfare);       // 街道
                           NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道
                           NSLog(@"locality,%@",place.locality);               // 市
                           NSLog(@"subLocality,%@",place.subLocality);         // 区
                           NSLog(@"country,%@",place.country);                 // 国家
                       }
                       
                   }];
    
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"location error :%@",error);
         
}

9、获取用户通讯录

/**
  获取用户的通讯录
 */
-(void)getUserContactList
{
    if (Is_up_Ios_9) {
        [self fetchContactListAfterIOS9];
    }else{
        [self fetchAddressBookBeforeIOS9];
    }
}
// -----------9.0以下的获取方式-------------
- (void)fetchAddressBookBeforeIOS9{
    ABAddressBookRef addressBook = ABAddressBookCreate();
    //用户授权
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {//首次访问通讯录
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            if (!error) {
                if (granted) {//允许
                    NSArray *contacts = [self fetchContactWithAddressBook:addressBook];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSLog(@"contacts:%@", contacts);
                    });
                }else{//拒绝
                }
            }else{
                NSLog(@"访问通讯录错误 before ios9= %@",error);
            }
        });
    }else{//非首次访问通讯录
        NSArray *contacts = [self fetchContactWithAddressBook:addressBook];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"contacts:%@", contacts);
        });
    }
}

- (NSMutableArray *)fetchContactWithAddressBook:(ABAddressBookRef)addressBook{
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {////有权限访问
        //获取联系人数组
        NSArray *array = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
        NSMutableArray *contacts = [NSMutableArray array];
        for (int i = 0; i < array.count; i++) {
            //获取联系人
            ABRecordRef people = CFArrayGetValueAtIndex((__bridge ABRecordRef)array, i);
            //获取联系人详细信息,如:姓名,电话,住址等信息
            NSString *firstName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonFirstNameProperty);
            NSString *lastName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonLastNameProperty);
            ABMutableMultiValueRef *phoneNumRef = ABRecordCopyValue(people, kABPersonPhoneProperty);
            NSString *phoneNumber =  ((__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(phoneNumRef)).lastObject;
            [contacts addObject:@{@"name": [firstName stringByAppendingString:lastName], @"phoneNumber": phoneNumber}];
        }
        return contacts;
    }else{//无权限访问
        NSLog(@"无权限访问通讯录");
        return nil;
    }
}
// -----------9.0以上的获取方式-------------

-(void)fetchContactListAfterIOS9
{
    CNContactStore *contact = [[CNContactStore alloc]init];
    if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]==CNAuthorizationStatusNotDetermined) {//首次访问通讯录
        [contact requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
                if (granted) {//允许
                    CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
                    contactPicker.delegate = self;
                    contactPicker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
                }else{//拒绝
                    
                }
            }else{
                NSLog(@"访问通讯录错误 after ios9= %@",error);
            }
            
        }];
    }else if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]==CNAuthorizationStatusAuthorized){//不是首次访问通讯录
        CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
        contactPicker.delegate = self;
        contactPicker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
    }else{
        NSLog(@"无权访问通讯录");
    }
}
#pragma mark -- CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {
    CNPhoneNumber *phoneNumber = (CNPhoneNumber *)contactProperty.value;
    /// 联系人
    NSString *text1 = [NSString stringWithFormat:@"%@%@",contactProperty.contact.familyName,contactProperty.contact.givenName];
    /// 电话
    NSString *text2 = phoneNumber.stringValue;
    //        text2 = [text2 stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSLog(@"联系人:%@, 电话:%@",text1,text2);
}

10、获取设备当前网络IP地址

#pragma mark - 获取设备当前网络IP地址
+ (NSString *)getIPAddress:(BOOL)preferIPv4
{
    //判断网络类型:wifi
    if ([PPCAppBaseInfo shareBaseInfo].networkType==1) {
        NSArray *searchArray = preferIPv4 ?
        @[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
        @[ IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
        
        NSDictionary *addresses = [self getIPAddresses];
        //    NSPPCLog(@"addresses: %@", addresses);
        
        __block NSString *address;
        [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
         {
             address = addresses[key];
             //筛选出IP地址格式
             if([self isValidatIP:address]) *stop = YES;
         } ];
//             NSPPCLog(@"ip = %@", address);
        return address ? address : @"0.0.0.0";
    }
    //wann
    return [self deviceWANIPAddress];
}

+ (BOOL)isValidatIP:(NSString *)ipAddress {
    if (ipAddress.length == 0) {
        return NO;
    }
    NSString *urlRegEx = @"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
    
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlRegEx options:0 error:&error];
    
    if (regex != nil) {
        NSTextCheckingResult *firstMatch=[regex firstMatchInString:ipAddress options:0 range:NSMakeRange(0, [ipAddress length])];
        
        if (firstMatch) {
//            NSRange resultRange = [firstMatch rangeAtIndex:0];
//            NSString *result=[ipAddress substringWithRange:resultRange];
            //输出结果
//            NSPPCLog(@"%@",result);
            return YES;
        }
    }
    return NO;
}

+ (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    
    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}

//wann
+(NSString *)deviceWANIPAddress
{
    NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
    NSData *data = [NSData dataWithContentsOfURL:ipURL];
    NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//    NSLog(@"ip = %@",(ipDic[@"data"][@"ip"] ? ipDic[@"data"][@"ip"] : @""));
    return (ipDic[@"data"][@"ip"] ? ipDic[@"data"][@"ip"] : @"0.0.0.0");
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,723评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,080评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,604评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,440评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,431评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,499评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,893评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,541评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,751评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,547评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,619评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,320评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,890评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,896评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,137评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,796评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,335评论 2 342

推荐阅读更多精彩内容

  • 1、获取设备的信息 2、获取设备的唯一标示符 3、为系统创建一个随机的标示符 5、获取运营商的信息 首先需要导入系...
    Young_Blood阅读 2,011评论 8 4
  • iOS获取设备信息 在iOS开发过程中,有时我们想获取到设备的系统信息,这时就需要使用到UIDevice类,具体常...
    蚊香酱阅读 1,634评论 4 10
  • 这里只介绍一些获取设备的一些基本信息,像IMEI、MAC地址等一些被苹果禁掉获取的信息就不作介绍了。虽然这些可以通...
    ZJ_偶尔上路阅读 799评论 0 1
  • #pragma mark----获取设备型号 + (NSString *)deviceModel{ return ...
    彬至睢阳阅读 536评论 0 0
  • 转自si1ence 工作中遇到了统计用户信息、下发广告,服务器端的需求往往需要手机用户设备及app的各种信息。 D...
    linbj阅读 345评论 0 5