欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS相册、相机、通讯录权限获取

程序员文章站 2024-02-05 21:44:22
一、为什么要获取权限 在越来越注重个人隐私的今天,用户很多情况下希望自己能完全掌握自己手机应用对媒体信息的一些访问权限,比如相册、相机、通讯录等。苹果在ios7、ios8等几个版本对一些权限的控制都...

一、为什么要获取权限

在越来越注重个人隐私的今天,用户很多情况下希望自己能完全掌握自己手机应用对媒体信息的一些访问权限,比如相册、相机、通讯录等。苹果在ios7、ios8等几个版本对一些权限的控制都做了加强,需要用户授权后应用才有相关的访问权限。

场景:

在你获取相册数据的时候,如果用户拒绝授权,那么可能会获取不到数据,此时需要给用户相应的提示,告知用户是权限的问题,此时,就需要得知相应的权限状态给用户恰当的提示。

用户的设备没有相机输入设备,如果你想访问用户的相机,此时就需要判断用户设备是否支持,给出恰当的提示。

二、权限状态说明

相册、相机、通讯录等授权状态目前都有种,都可以对应以下几种状态:

authorizationstatusnotdetermined      // 用户从未进行过授权等处理,首次访问相应内容会提示用户进行授权
authorizationstatusauthorized = 0,    // 用户已授权,允许访问
authorizationstatusdenied,            // 用户拒绝访问
authorizationstatusrestricted,        // 应用没有相关权限,且当前用户无法改变这个权限,比如:家长控制

三、权限获取

相册权限

是否支持

[uiimagepickercontroller issourcetypeavailable:uiimagepickercontrollersourcetypephotolibrary]

获取权限状态

ios8以前

    alauthorizationstatus authstatus = [alassetslibrary authorizationstatus];

ios8及以后

    phauthorizationstatus authstatus = [phphotolibrary authorizationstatus];

请求权限

[phphotolibrary requestauthorization:^(phauthorizationstatus status) {
                }];

权限状态

ios8以前

typedef ns_enum(nsinteger, alauthorizationstatus) {
    alauthorizationstatusnotdetermined ns_enum_deprecated_ios(6_0, 9_0) = 0, // user has not yet made a choice with regards to this application
    alauthorizationstatusrestricted ns_enum_deprecated_ios(6_0, 9_0),        // this application is not authorized to access photo data.
                                            // the user cannot change this application’s status, possibly due to active restrictions
                                            //  such as parental controls being in place.
    alauthorizationstatusdenied ns_enum_deprecated_ios(6_0, 9_0),            // user has explicitly denied this application access to photos data.
    alauthorizationstatusauthorized ns_enum_deprecated_ios(6_0, 9_0)        // user has authorized this application to access photos data.
} ns_deprecated_ios(6_0, 9_0, "use phauthorizationstatus in the photos framework instead");

ios8及以后

typedef ns_enum(nsinteger, phauthorizationstatus) {
    phauthorizationstatusnotdetermined = 0, // user has not yet made a choice with regards to this application
    phauthorizationstatusrestricted,        // this application is not authorized to access photo data.
                                            // the user cannot change this application’s status, possibly due to active restrictions
                                            //   such as parental controls being in place.
    phauthorizationstatusdenied,            // user has explicitly denied this application access to photos data.
    phauthorizationstatusauthorized         // user has authorized this application to access photos data.
} ns_available_ios(8_0);

拍照权限

是否支持

[uiimagepickercontroller issourcetypeavailable:uiimagepickercontrollersourcetypecamera]

获取权限状态

avauthorizationstatus authstatus = [avcapturedevice authorizationstatusformediatype:avmediatypevideo];

请求权限

[phphotolibrary requestauthorization:^(phauthorizationstatus status) {
                }];

权限状态

typedef ns_enum(nsinteger, avauthorizationstatus) {
    avauthorizationstatusnotdetermined = 0,
    avauthorizationstatusrestricted,
    avauthorizationstatusdenied,
    avauthorizationstatusauthorized
} ns_available_ios(7_0) __tvos_prohibited;

通讯录权限

获取权限状态

ios9以前

abauthorizationstatus authstatus = abaddressbookgetauthorizationstatus();

ios9及以后

cnauthorizationstatus authstatus = [cncontactstore authorizationstatusforentitytype:cnentitytypecontacts];

请求权限

ios9以前

__block abaddressbookref addressbook = abaddressbookcreatewithoptions(null, null);
if (addressbook == null) {
    [self executecallback:callback status:wtauthorizationstatusnotsupport];
    return;
}
abaddressbookrequestaccesswithcompletion(addressbook, ^(bool granted, cferrorref error) {
    if (granted) {
        // 成功
    } else {
        // 失败
    }
    if (addressbook) {
        cfrelease(addressbook);
        addressbook = null;
    }
});

ios9及以后

cncontactstore *contactstore = [[cncontactstore alloc] init];
[contactstore requestaccessforentitytype:cnentitytypecontacts completionhandler:^(bool granted, nserror * _nullable error) {
    if (granted) {
        // 成功
    } else {
        // 失败
    }
}];

权限状态

ios9以前

typedef cf_enum(cfindex, abauthorizationstatus) {
    kabauthorizationstatusnotdetermined = 0,    // deprecated, use cnauthorizationstatusnotdetermined
    kabauthorizationstatusrestricted,           // deprecated, use cnauthorizationstatusrestricted
    kabauthorizationstatusdenied,               // deprecated, use cnauthorizationstatusdenied
    kabauthorizationstatusauthorized            // deprecated, use cnauthorizationstatusauthorized
} ab_deprecated("use cnauthorizationstatus");

ios9及以后

typedef ns_enum(nsinteger, cnauthorizationstatus)
{
/*! the user has not yet made a choice regarding whether the application may access contact data. */
cnauthorizationstatusnotdetermined = 0,
/*! the application is not authorized to access contact data.
*  the user cannot change this application’s status, possibly due to active restrictions such as parental controls being in place. */
cnauthorizationstatusrestricted,
/*! the user explicitly denied access to contact data for the application. */
cnauthorizationstatusdenied,
/*! the application is authorized to access contact data. */
cnauthorizationstatusauthorized
} ns_enum_available(10_11, 9_0);

四、拒绝授权的处理

用户拒绝授权后,如果访问相应内容可能会出现一些类似没有数据的情况,此时应该给用户提示,引导用户授权。

跳转到应用设置:

nsurl *settingurl = [nsurl urlwithstring:uiapplicationopensettingsurlstring];
if ([[uiapplication sharedapplication] canopenurl:settingurl]) {
    [[uiapplication sharedapplication] openurl:settingurl];
}

五、简单封装示例

工具类

wtauthorizationtool.h文件

#import 


typedef ns_enum(nsuinteger, wtauthorizationstatus) {
    wtauthorizationstatusauthorized = 0,    // 已授权
    wtauthorizationstatusdenied,            // 拒绝
    wtauthorizationstatusrestricted,        // 应用没有相关权限,且当前用户无法改变这个权限,比如:家长控制
    wtauthorizationstatusnotsupport         // 硬件等不支持
};

@interface wtauthorizationtool : nsobject

/**
 *  请求相册访问权限
 *
 *  @param callback <#callback description#>
 */
+ (void)requestimagepickerauthorization:(void(^)(wtauthorizationstatus status))callback;

/**
 *  请求相机权限
 *
 *  @param callback <#callback description#>
 */
+ (void)requestcameraauthorization:(void(^)(wtauthorizationstatus status))callback;

+ (void)requestaddressbookauthorization:(void (^)(wtauthorizationstatus))callback;

@end

wtauthorizationtool.m文件

#import "wtauthorizationtool.h"



#import 


#import 


#import 


#import 


#import 


@implementation wtauthorizationtool


#pragma mark - 相册

+ (void)requestimagepickerauthorization:(void(^)(wtauthorizationstatus status))callback {
    if ([uiimagepickercontroller issourcetypeavailable:uiimagepickercontrollersourcetypecamera] ||
        [uiimagepickercontroller issourcetypeavailable:uiimagepickercontrollersourcetypephotolibrary]) {
        alauthorizationstatus authstatus = [alassetslibrary authorizationstatus];
        if (authstatus == alauthorizationstatusnotdetermined) { // 未授权
            if ([uidevice currentdevice].systemversion.floatvalue < 8.0) {
                [self executecallback:callback status:wtauthorizationstatusauthorized];
            } else {
                [phphotolibrary requestauthorization:^(phauthorizationstatus status) {
                    if (status == phauthorizationstatusauthorized) {
                        [self executecallback:callback status:wtauthorizationstatusauthorized];
                    } else if (status == phauthorizationstatusdenied) {
                        [self executecallback:callback status:wtauthorizationstatusdenied];
                    } else if (status == phauthorizationstatusrestricted) {
                        [self executecallback:callback status:wtauthorizationstatusrestricted];
                    }
                }];
            }

        } else if (authstatus == alauthorizationstatusauthorized) {
            [self executecallback:callback status:wtauthorizationstatusauthorized];
        } else if (authstatus == alauthorizationstatusdenied) {
            [self executecallback:callback status:wtauthorizationstatusdenied];
        } else if (authstatus == alauthorizationstatusrestricted) {
            [self executecallback:callback status:wtauthorizationstatusrestricted];
        }
    } else {
        [self executecallback:callback status:wtauthorizationstatusnotsupport];
    }
}


#pragma mark - 相机

+ (void)requestcameraauthorization:(void (^)(wtauthorizationstatus))callback {
    if ([uiimagepickercontroller issourcetypeavailable:uiimagepickercontrollersourcetypecamera]) {
        avauthorizationstatus authstatus = [avcapturedevice authorizationstatusformediatype:avmediatypevideo];
        if (authstatus == avauthorizationstatusnotdetermined) {
            [avcapturedevice requestaccessformediatype:avmediatypevideo completionhandler:^(bool granted) {
                if (granted) {
                    [self executecallback:callback status:wtauthorizationstatusauthorized];
                } else {
                    [self executecallback:callback status:wtauthorizationstatusdenied];
                }
            }];
        } else if (authstatus == avauthorizationstatusauthorized) {
            [self executecallback:callback status:wtauthorizationstatusauthorized];
        } else if (authstatus == avauthorizationstatusdenied) {
            [self executecallback:callback status:wtauthorizationstatusdenied];
        } else if (authstatus == avauthorizationstatusrestricted) {
            [self executecallback:callback status:wtauthorizationstatusrestricted];
        }
    } else {
        [self executecallback:callback status:wtauthorizationstatusnotsupport];
    }
}


#pragma mark - 通讯录

+ (void)requestaddressbookauthorization:(void (^)(wtauthorizationstatus))callback {
    abauthorizationstatus authstatus = abaddressbookgetauthorizationstatus();
    if (authstatus == kabauthorizationstatusnotdetermined) {
        __block abaddressbookref addressbook = abaddressbookcreatewithoptions(null, null);
        if (addressbook == null) {
            [self executecallback:callback status:wtauthorizationstatusnotsupport];
            return;
        }
        abaddressbookrequestaccesswithcompletion(addressbook, ^(bool granted, cferrorref error) {
            if (granted) {
                [self executecallback:callback status:wtauthorizationstatusauthorized];
            } else {
                [self executecallback:callback status:wtauthorizationstatusdenied];
            }
            if (addressbook) {
                cfrelease(addressbook);
                addressbook = null;
            }
        });
        return;
    } else if (authstatus == kabauthorizationstatusauthorized) {
        [self executecallback:callback status:wtauthorizationstatusauthorized];
    } else if (authstatus == kabauthorizationstatusdenied) {
        [self executecallback:callback status:wtauthorizationstatusdenied];
    } else if (authstatus == kabauthorizationstatusrestricted) {
        [self executecallback:callback status:wtauthorizationstatusrestricted];
    }
}


#pragma mark - callback

+ (void)executecallback:(void (^)(wtauthorizationstatus))callback status:(wtauthorizationstatus)status {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (callback) {
                callback(status);
        }
    });
}

@end

界面测试提示

controller部分代码

- (void)requestaddressbook {
    [wtauthorizationtool requestaddressbookauthorization:^(wtauthorizationstatus status) {
        [self requestauthcallback:status];
    }];
}

- (void)requestcamera {
    [wtauthorizationtool requestcameraauthorization:^(wtauthorizationstatus status) {
        [self requestauthcallback:status];
    }];
}

- (void)requestalbum {
    [wtauthorizationtool requestimagepickerauthorization:^(wtauthorizationstatus status) {
        [self requestauthcallback:status];
    }];
}

- (void)requestauthcallback:(wtauthorizationstatus)status {
    switch (status) {
        case wtauthorizationstatusauthorized:
            [wtalert showalertfrom:self title:@"授权成功" message:@"可以访问你要访问的内容了" cancelbuttontitle:@"我知道了" cancle:^{

            } confirmbuttontitle:nil confirm:nil];
            break;

        case wtauthorizationstatusdenied:
        case wtauthorizationstatusrestricted:
            [wtalert showalertfrom:self title:@"授权失败" message:@"用户拒绝" cancelbuttontitle:@"我知道了" cancle:^{

            } confirmbuttontitle:@"现在设置" confirm:^{
                nsurl *settingurl = [nsurl urlwithstring:uiapplicationopensettingsurlstring];
                if ([[uiapplication sharedapplication] canopenurl:settingurl]) {
                    [[uiapplication sharedapplication] openurl:settingurl];
                }
            }];
            break;

        case wtauthorizationstatusnotsupport:
            [wtalert showalertfrom:self title:@"授权失败" message:@"设备不支持" cancelbuttontitle:@"我知道了" cancle:^{

            } confirmbuttontitle:nil confirm:nil];

        default:
            break;
    }
}

源码">六、源码

完整源码

使用wtauthorizationtool

pod "wtauthorizationtool"