美文网首页
ios获取设备信息

ios获取设备信息

作者: 呆呆滴木木菇凉 | 来源:发表于2016-12-12 11:20 被阅读0次

    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");
    }
    

    相关文章

      网友评论

          本文标题:ios获取设备信息

          本文链接:https://www.haomeiwen.com/subject/nrdmmttx.html