我有一个设置视图,用户可以 Select 打开或关闭功能"Export to Camera Roll"

当用户第一次打开它时(而不是在他拍摄第一张照片时),我希望该应用程序向他请求访问相机卷的权限.

我在很多应用程序中都见过这种行为,但都找不到方法.

推荐答案

我不确定是否有一些内置的方法来实现这一点,但一个简单的方法是在打开该功能时使用AlassetLibrary从照片库中提取一些无意义的信息.然后,你可以简单地取消你所获取的任何信息,你就会提示用户访问他们的照片.

例如,下面的代码只获取相机卷中的照片数量,但足以触发权限提示.

#import <AssetsLibrary/AssetsLibrary.h>

ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
[lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
    NSLog(@"%zd", [group numberOfAssets]);
} failureBlock:^(NSError *error) {
    if (error.code == ALAssetsLibraryAccessUserDeniedError) {
        NSLog(@"user denied access, code: %zd", error.code);
    } else {
        NSLog(@"Other error code: %zd", error.code);
    }
}];

EDIT:刚刚偶然发现这一点,下面是如何判断应用程序访问相册的授权状态.

ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];

if (status != ALAuthorizationStatusAuthorized) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Attention" message:@"Please give this app permission to access your photo library in your settings app!" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
    [alert show];
}

Objective-c相关问答推荐

将谷歌 map 添加为子视图会使 iOS 应用程序因 exc_bad 崩溃

如何通过仅更改高度而不更改宽度来调整 UILabel 的大小?

从 C# 到 Objective C 会有多大的飞跃

Xcode 中架构的重复符号

将 HEX NSString 转换为 NSData

iOS performSelectorOnMainThread 有多个参数

在 UITableViewCells 上显示复制弹出窗口的简单方法,如地址簿应用程序

UIRefreshControl - 在 iOS 7 中 pull 刷新

用于 iOS 开发的 LLVM 与 GCC

未知类型名称类;您指的是 'Class' 吗?

检测 iOS 应用程序是否在调试器中运行

获取包含在 NSString 中的文件的扩展名

NSURLConnection sendAsynchronousRequest:queue:completionHandler:连续发出多个请求?

如何在 Objective C 中将浮点数转换为 int?

导航返回时重新加载 UITableView?

当 UIView 框架更改时,视图内的 AVPlayer 层不会调整大小

如何删除 UIToolBar 上的顶部边框

如何将 printf 与 NSString 一起使用

@synthesized 保留属性的释放是如何处理的?

UiTextField 中的第一个字母小写