iOS高级进阶iOS Developer

iOS 获取相机、相册权限

2016-12-01  本文已影响143人  南城同學
为了方便全局的使用,建议写到工具类中,如果只是单单的查询授权可以基于UIApplication写一个分类;如下:
#import <UIKit/UIKit.h>
#import <Photos/Photos.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
@interface UIApplication (GetRight)

/**
 *  获取相机的授权
 *  @return YES/NO
 */
- (BOOL)getCameraRight;

/**
 *  获取相册的授权
 *  @return YES/NO
 */
- (BOOL)getAlbumRight;

@end
#import "UIApplication+ GetRight.h"
@implementation UIApplication (GetRight)

#pragma mark - 相机授权
- (BOOL)getCameraRight {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
        return NO;
    } else {
        return YES;
    }
}

#pragma mark - 相册授权
- (BOOL)getAlbumRight{
    PHAuthorizationStatus author = [PHPhotoLibrary authorizationStatus];
    if (author == PHAuthorizationStatusRestricted || author == PHAuthorizationStatusDenied) {
        return NO;
    }else{
        return YES;
    }
}
@end

使用:
 if ([[UIApplication sharedApplication] getCameraRight]) {
       NSLog(@"用户允许访问相机");
    } else {
       NSLog(@"没有权限");
    }
}   
 
if ([[UIApplication sharedApplication] getAlbumRight]) {
      NSLog(@"用户允许访问相册");
    } else {
      NSLog(@"没有权限");
    }
}

注:如果编译工具是Xcode8,请在info.plist中添加如下两个key:

屏幕快照 2016-12-02 下午1.55.58.png
上一篇 下一篇

猜你喜欢

热点阅读