美文网首页
iOS-获取手机信息等常见功能整理一

iOS-获取手机信息等常见功能整理一

作者: 见哥哥长高了 | 来源:发表于2019-06-28 08:53 被阅读0次

    开发的过程当中,有些时候会用到手机系统或者App本身的一些信息。例如:手机型号、手机系统版本等。下面是常用的获取方法:

    获取手机型号
    + (NSString *)iphoneType{
        struct utsname systemInfo;
        uname(&systemInfo);
        NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
        //iPhone
        if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
         ...
         //其他对应关系请看下面对应表    
        return platform;
    }
    

    iPhone设备类型与通用手机类型一一对应关系表
    设备类型 通用类型
    iPhone1,1 iPhone 1G
    iPhone1,2 iPhone 3G
    iPhone2,1 iPhone 3GS
    iPhone3,1 iPhone 4
    iPhone3,2 iPhone 4
    iPhone4,1 iPhone 4S
    iPhone5,1 iPhone 5
    iPhone5,2 iPhone 5
    iPhone5,3 iPhone 5C
    iPhone5,4 iPhone 5C
    iPhone6,1 iPhone 5S
    iPhone6,2 iPhone 5S
    iPhone7,1 iPhone 6 Plus
    iPhone7,2 iPhone 6
    iPhone8,1 iPhone 6S
    iPhone8,2 iPhone 6S Plus
    iPhone8,4 iPhone SE
    iPhone9,1 iPhone 7
    iPhone9,3 iPhone 7
    iPhone9,2 iPhone 7 Plus
    iPhone9,4 iPhone 7 Plus
    iPhone10,1 iPhone 8
    iPhone10.4 iPhone 8
    iPhone10,2 iPhone 8 Plus
    iPhone10,5 iPhone 8 Plus
    iPhone10,3 iPhone X
    iPhone10,6 iPhone X
    iPhone11,8 iPhone XR
    iPhone11,2 iPhone XS
    iPhone11,4 iPhone XS Max
    Phone11,6 iPhone XS Max

    获取手机系统版本
    NSString *phoneVersion = [[UIDevice currentDevice] systemVersion];
    
    获取App BundleId
    NSString *bundleId = [[NSBundle mainBundle] bundleIdentifier];
    
    获取App 版本号
    NSString *bundleVersionCode = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleVersion"];
    
    权限信息查看

    应用程序在iOS系统下,如果想要获取隐私权限的话,需要征得用户的同意。最常见的就是给出权限提醒,用户给出权限,应用即可使用,但是如果用户拒绝,则相应的功能就受限了。但是有的时候我们要用到一个功能的时候,需要首先判断用户是否同意了程序使用相关权限。系统的权限种类有很多。例如:网络权限,相机权限,麦克风权限,相册权限,地理位置,日历,联系人,蓝牙等。下面举几个常见的判断手机权限的例子:

    /*
     *相册权限
     */
    - (void)permissionTypePhotoAction{
        PHAuthorizationStatus photoStatus = [PHPhotoLibrary authorizationStatus];
        __block LGJPermissionManager *weakSelf = self;
        if (photoStatus == PHAuthorizationStatusNotDetermined) {
            
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (status == PHAuthorizationStatusAuthorized) {
                    weakSelf.block(YES, @(photoStatus));
                } else {
                    weakSelf.block(NO, @(photoStatus));
                }
            }];
        } else if (photoStatus == PHAuthorizationStatusAuthorized) {
            self.block(YES, @(photoStatus));
        } else if(photoStatus == PHAuthorizationStatusRestricted||photoStatus == PHAuthorizationStatusDenied){
            self.block(NO, @(photoStatus));
            [self pushSetting:@"相册权限"];
            
        }else{
            self.block(NO, @(photoStatus));
        }
    }
    
    
    /*
     *相机权限
     */
    - (void)permissionTypeCameraAction{
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        __block LGJPermissionManager *weakSelf = self;
        if(authStatus == AVAuthorizationStatusNotDetermined){
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                weakSelf.block(granted, @(authStatus));
            }];
        }  else if (authStatus == AVAuthorizationStatusAuthorized) {
            self.block(YES, @(authStatus));
        } else if(authStatus == AVAuthorizationStatusRestricted||authStatus == AVAuthorizationStatusDenied){
            self.block(NO, @(authStatus));
            [self pushSetting:@"相机权限"];
            
        }else{
            self.block(NO, @(authStatus));
        }
    }
    
    /*
     *麦克风权限
     */
    - (void)permissionTypeMicAction{
        AVAudioSessionRecordPermission micPermisson = [[AVAudioSession sharedInstance] recordPermission];
        __block LGJPermissionManager *weakSelf = self;
        if (micPermisson == AVAudioSessionRecordPermissionUndetermined) {
            [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                weakSelf.block(granted, @(micPermisson));
            }];
        } else if (micPermisson == AVAudioSessionRecordPermissionGranted) {
            self.block(YES, @(micPermisson));
        } else {
            self.block(NO, @(micPermisson));
            [self pushSetting:@"麦克风权限"];
        }
    }
    
    
    /*
     *获取地理位置When
     */
    - (void)permissionTypeLocationWhenAction{
        
        if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
            NSLog(@"能进行定位...");
            if (self.block) {
                self.block(YES, nil);
            }
        }else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
            NSLog(@"不能进行定位...");
            if (self.block) {
                self.block(NO, nil);
            }
            if (self.isShow == YES) {
                [self remindUserToGiveAutAuthorityOfLocation];
            }
        }
        
    //    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    //    if (status == kCLAuthorizationStatusNotDetermined) {
    //
    //    } else if (status == kCLAuthorizationStatusAuthorizedWhenInUse){
    //        self.block (YES, @(status));
    //    } else {
    //        self.block(NO, @(status));
    //        [self pushSetting:@"使用期间访问地理位置权限"];
    //    }
    }
    
    
    
    /*
     *日历
     */
    - (void)permissionTypeCalendarAction{
        EKEntityType type  = EKEntityTypeEvent;
        __block LGJPermissionManager *weakSelf = self;
        EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:type];
        if (status == EKAuthorizationStatusNotDetermined) {
            EKEventStore *eventStore = [[EKEventStore alloc] init];
            [eventStore requestAccessToEntityType:type completion:^(BOOL granted, NSError * _Nullable error) {
                weakSelf.block(granted,@(status));
            }];
        } else if (status == EKAuthorizationStatusAuthorized) {
            self.block(YES,@(status));
        } else {
            [self pushSetting:@"日历权限"];
            self.block(NO,@(status));
        }
    }
    
    /*
     *联系人
     */
    - (void)permissionTypeContactsAction{
        CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
        __block LGJPermissionManager *weakSelf = self;
        if (status == CNAuthorizationStatusNotDetermined) {
            CNContactStore *store = [[CNContactStore alloc] init];
            [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    weakSelf.block(granted,[weakSelf openContact]);
                }
                weakSelf.block(granted,@(status));
            }];
        } else if (status == CNAuthorizationStatusAuthorized) {;
            self.block(YES,[self openContact]);
        } else {
            self.block(NO,@(status));
            [self pushSetting:@"联系人权限"];
        }
    }
    
    /*
     * 提醒
     */
    - (void)permissionTypeRemainerAction{
        EKEntityType type  = EKEntityTypeReminder;
        __block LGJPermissionManager *weakSelf = self;
        EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:type];
        if (status == EKAuthorizationStatusNotDetermined) {
            EKEventStore *eventStore = [[EKEventStore alloc] init];
            [eventStore requestAccessToEntityType:type completion:^(BOOL granted, NSError * _Nullable error) {
                weakSelf.block(granted,@(status));
            }];
        } else if (status == EKAuthorizationStatusAuthorized) {
            self.block(YES,@(status));
        } else {
            [self pushSetting:@"日历权限"];
            self.block(NO,@(status));
        }
    }
    
    /*
     * 健康
     */
    - (void)permissionTypeHealthAction{
        //查看healthKit在设备上是否可用,ipad不支持HealthKit
        if (![HKHealthStore isHealthDataAvailable]) {
            NSLog(@"设备不支持healthKit");
            self.block(NO, nil);
            return;
        }
    
        if (!self.healthStore) {
            self.healthStore = [HKHealthStore new];
        }
    
    
        HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
        __block LGJPermissionManager *weakSelf = self;
        NSSet *readDataTypes =  [NSSet setWithObjects:stepType, nil];
        [self.healthStore requestAuthorizationToShareTypes:nil readTypes:readDataTypes completion:^(BOOL success, NSError * _Nullable error) {
    
            if (success) {
                [weakSelf readStepCount];
            }else{
                weakSelf.block(NO, nil);
            }
        }];
    }
    
    /*
     * 多媒体
     */
    - (void)permissionTypeMediaLibraryAction{
        __block LGJPermissionManager *weakSelf = self;
        [MPMediaLibrary requestAuthorization:^(MPMediaLibraryAuthorizationStatus status){
            switch (status) {
                case MPMediaLibraryAuthorizationStatusNotDetermined: {
                    weakSelf.block(NO, @(status));
                    break;
                }
                case MPMediaLibraryAuthorizationStatusRestricted: {
                    weakSelf.block(NO, @(status));
                    break;
                }
                case MPMediaLibraryAuthorizationStatusDenied: {
                    weakSelf.block(NO, @(status));
                    break;
                }
                case MPMediaLibraryAuthorizationStatusAuthorized: {
                    // authorized
                    weakSelf.block(YES, @(status));
                    break;
                }
                default: {
                    break;
                }
            }
    
        }];
    }
    
    /*
     * 查询步数数据
     */
    - (void)readStepCount
    {
        HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
        NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];
    
        __block LGJPermissionManager *weakSelf = self;
        HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:stepType predicate:[LGJPermissionManager predicateForSamplesToday] limit:HKObjectQueryNoLimit sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
            if(error)
            {
    
                weakSelf.block(NO, error);
            }
            else
            {
                NSInteger totleSteps = 0;
                for(HKQuantitySample *quantitySample in results)
                {
                    HKQuantity *quantity = quantitySample.quantity;
                    HKUnit *heightUnit = [HKUnit countUnit];
                    double usersHeight = [quantity doubleValueForUnit:heightUnit];
                    totleSteps += usersHeight;
                }
                NSLog(@"当天行走步数 = %ld",(long)totleSteps);
                weakSelf.block(YES,@(totleSteps));
            }
        }];
    
        [self.healthStore executeQuery:query];
    
    
    }
    
    /*!
     *  @brief  当天时间段(可以获取某一段时间)
     *
     *  @return 时间段
     */
    + (NSPredicate *)predicateForSamplesToday {
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDate *now = [NSDate date];
        NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
        [components setHour:0];
        [components setMinute:0];
        [components setSecond: 0];
    
        NSDate *startDate = [calendar dateFromComponents:components];
        NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
        NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];
        return predicate;
    }
    
    
    //有通讯录权限-- 获取通讯录
    - (NSArray*)openContact{
        // 获取指定的字段
        NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
        CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
        CNContactStore *contactStore = [[CNContactStore alloc] init];
        NSMutableArray *arr = [NSMutableArray new];
        [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
            //拼接姓名
            NSString *nameStr = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
    
            NSArray *phoneNumbers = contact.phoneNumbers;
    
            for (CNLabeledValue *labelValue in phoneNumbers) {
                CNPhoneNumber *phoneNumber = labelValue.value;
                NSString * string = phoneNumber.stringValue ;
                //去掉电话中的特殊字符
                string = [string stringByReplacingOccurrencesOfString:@"+86" withString:@""];
                string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
                string = [string stringByReplacingOccurrencesOfString:@"(" withString:@""];
                string = [string stringByReplacingOccurrencesOfString:@")" withString:@""];
                string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
                string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
                NSLog(@"姓名=%@, 电话号码是=%@", nameStr, string);
                [arr addObject:@{@"name":nameStr,@"phone":string}];
            }
        }];
        return [NSArray arrayWithArray:arr];
    
    }
    
    
    #pragma mark - CLLocationManagerDelegate
    
    - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
    {
        self.block(YES, error);
    }
    
    
    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations{
            self.block(YES, locations.firstObject);
            [self stopLocationService];
    }
    
    
    - (void)stopLocationService
    {
        [self.locationManager stopUpdatingLocation];
        self.locationManager.delegate=nil;
        self.locationManager = nil;
    }
    
    #pragma mark - CBCentralManagerDelegate
    -(void)centralManagerDidUpdateState:(CBCentralManager *)central
    {
        //蓝牙第一次以及之后每次蓝牙状态改变都会调用这个函数
        if(central.state==CBManagerStatePoweredOn)
        {
            NSLog(@"蓝牙设备开着");
            self.block(YES, nil);
        }
        else
        {
            NSLog(@"蓝牙设备关着");
            self.block(NO, nil);
        }
    }
    
    
    /*
     *跳转设置
     */
    - (void)pushSetting:(NSString*)urlStr{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@%@",urlStr,self.tip] preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancelAction];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url= [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if (IOS_10_OR_LATER) {
                if( [[UIApplication sharedApplication]canOpenURL:url] ) {
                    [[UIApplication sharedApplication]openURL:url options:@{}completionHandler:^(BOOL        success) {
                    }];
                }
            }else{
                if( [[UIApplication sharedApplication]canOpenURL:url] ) {
                    [[UIApplication sharedApplication]openURL:url options:@{} completionHandler:nil];
                }
            }
        }];
        [alert addAction:okAction];
        [[LGJPermissionManager getCurrentVC] presentViewController:alert animated:YES completion:nil];
    }
    
    //获取当前VC
    + (UIViewController *)getCurrentVC
    {
        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        
        UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
        
        return currentVC;
    }
    
    + (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
    {
        UIViewController *currentVC;
        
        if ([rootVC presentedViewController]) {
            // 视图是被presented出来的
            rootVC = [rootVC presentedViewController];
        }
        
        if ([rootVC isKindOfClass:[UITabBarController class]]) {
            // 根视图为UITabBarController
            currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
            
        } else if ([rootVC isKindOfClass:[UINavigationController class]]){
            // 根视图为UINavigationController
            currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
            
        } else {
            // 根视图为非导航类
            currentVC = rootVC;
        }
        return currentVC;
    }
    
    - (NSString *)tip{
        if (!_tip) {
            _tip = @"尚未开启,是否前往设置";
        }
        return _tip;
    }
    
    
    分享功能

    利用UIActivityViewController类可以轻松实现分享功能


    系统文件分享

    以下是实现代码:

    - (IBAction)click:(UIButton *)sender {
        
        NSURL *url = [NSURL fileURLWithPath:@"/Users/adiqueen/Desktop/LGJDemo/LGJDemo/[Android开发从入门到精通].扶松柏.扫描版.pdf"];
        NSArray *objectsToShare = @[url];
        
        UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
        NSArray *excludedActivities = @[UIActivityTypePostToTwitter, UIActivityTypePostToFacebook,
                                        UIActivityTypePostToWeibo,
                                        UIActivityTypeMessage, UIActivityTypeMail,
                                        UIActivityTypePrint, UIActivityTypeCopyToPasteboard,
                                        UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll,
                                        UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr,
                                        UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo];
        controller.excludedActivityTypes = excludedActivities;
        
        [self presentViewController:controller animated:YES completion:nil];
        
    }
    

    相关文章

      网友评论

          本文标题:iOS-获取手机信息等常见功能整理一

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