iOS17调用fetchAssetCollectionsWithType崩溃,报错照片库暂不可访问
iOS 17调用
fetchAssetCollectionsWithType崩溃的问题排查与解决 问题复现
以下代码在iOS 17系统调用fetchAssetCollectionsWithType时崩溃,错误提示:
Access to the photo library is not allowed until the photo library is obtainable
PHAuthorizationStatus authorizationStatus = [PHPhotoLibrary authorizationStatusForAccessLevel:PHAccessLevelReadWrite]; if (authorizationStatus != PHAuthorizationStatusAuthorized) { return; } PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init]; fetchOptions.predicate = [NSPredicate predicateWithFormat:@"title == %@", "MyAlbum"]; PHFetchResult *collections = [PHAssetCollection fetchAssetCollectionsWithType: PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:fetchOptions];
调整调用时机到viewDidLoad之后仍出现错误。
问题原因
iOS 17照片库访问逻辑变更:
iOS 17之后,仅通过authorizationStatusForAccessLevel检查授权状态不足以确保照片库已完全可用。即使授权状态为Authorized,照片库可能仍在后台初始化,同步调用照片库操作会触发崩溃。代码语法错误:
代码中predicateWithFormat的第二个参数使用了C字符串"MyAlbum",而Objective-C中需要传入NSString类型的@"MyAlbum",这会导致运行时错误,可能加剧崩溃问题。
解决方案
1. 使用异步方式确保照片库可用
iOS 17推荐使用PHPhotoLibrary的异步方法来确认库实例就绪后再执行操作:
// 先检查并处理授权状态 PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatusForAccessLevel:PHAccessLevelReadWrite]; if (status == PHAuthorizationStatusNotDetermined) { [PHPhotoLibrary requestAuthorizationForAccessLevel:PHAccessLevelReadWrite handler:^(PHAuthorizationStatus authStatus) { if (authStatus == PHAuthorizationStatusAuthorized) { [self fetchTargetAlbum]; } }]; } else if (status == PHAuthorizationStatusAuthorized) { [self fetchTargetAlbum]; } // 确保照片库可用后执行查询 - (void)fetchTargetAlbum { [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ // 空操作触发照片库初始化确认 } completionHandler:^(BOOL success, NSError * _Nullable error) { if (success) { dispatch_async(dispatch_get_main_queue(), ^{ PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init]; fetchOptions.predicate = [NSPredicate predicateWithFormat:@"title == %@", @"MyAlbum"]; PHFetchResult *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:fetchOptions]; // 处理查询结果 if (collections.count > 0) { // 找到目标相册,执行后续逻辑 } }); } }]; }
2. 修复字符串语法错误
将"MyAlbum"替换为Objective-C字符串字面量@"MyAlbum",避免类型不匹配导致的运行时错误。
总结
iOS 17对照片库访问增加了初始化状态检查,必须确保库完全就绪后再执行查询操作;同时修正代码中的语法错误,即可解决崩溃问题。
内容的提问来源于stack exchange,提问作者Jhon Liang Leo
相关产品推荐
相关产品推荐

