【发布时间】:2016-08-10 11:18:45
【问题描述】:
当有一个图库应用程序时,我可以在其中显示相机胶卷中的所有图像和视频。
如果我截取屏幕截图,该应用程序将无法正常运行,因为相机胶卷发生了变化。
它崩溃的原因是photoLibraryDidChange函数。
如果我退出程序拍照并重新打开它,一切正常,但是当我截取屏幕截图时,我的程序会多次进入此功能,而不仅仅是一次。
我该如何解决?
【问题讨论】:
标签: ios photosframework
当有一个图库应用程序时,我可以在其中显示相机胶卷中的所有图像和视频。
如果我截取屏幕截图,该应用程序将无法正常运行,因为相机胶卷发生了变化。
它崩溃的原因是photoLibraryDidChange函数。
如果我退出程序拍照并重新打开它,一切正常,但是当我截取屏幕截图时,我的程序会多次进入此功能,而不仅仅是一次。
我该如何解决?
【问题讨论】:
标签: ios photosframework
您必须为 PhotoLibrary 添加更改观察者,并实现相关功能以接收更改。 例如:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
}
然后,覆盖协议PHPhotoLibraryChangeObserver的didChange方法。
#pragma mark - <PHPhotoLibraryChangeObserver>
- (void)photoLibraryDidChange:(PHChange *)changeInstance
{
// Check if there are changes to the assets we are showing.
PHFetchResultChangeDetails *collectionChanges = [changeInstance changeDetailsForFetchResult:_fetchResult];
if (collectionChanges == nil) {
return;
}
// Get the new fetch result.
_fetchResult = [collectionChanges fetchResultAfterChanges];
/*
Change notifications may be made on a background queue. Re-dispatch to the
main queue before acting on the change as we'll be updating the UI.
*/
dispatch_async(dispatch_get_main_queue(), ^{
if (!_isCollectionViewLoaded) {
return ;
}
UICollectionView *collectionView = _collectionView;
if (![collectionChanges hasIncrementalChanges] || [collectionChanges hasMoves]) {
// Reload the collection view if the incremental diffs are not available
[collectionView reloadData];
} else {
/*
Tell the collection view to animate insertions and deletions if we
have incremental diffs.
*/
NSArray<NSIndexPath *> * removedPaths = [[collectionChanges removedIndexes] aapl_indexPathsFromIndexesWithSection:0];
NSArray<NSIndexPath *> * insertedPaths = [[collectionChanges insertedIndexes] aapl_indexPathsFromIndexesWithSection:0];
NSArray<NSIndexPath *> * changedPaths = [[collectionChanges changedIndexes] aapl_indexPathsFromIndexesWithSection:0];
BOOL shouldReload = NO;
if ((changedPaths != nil) + (removedPaths != nil) + (insertedPaths!= nil) > 1) {
shouldReload = YES;
}
if (shouldReload) {
[collectionView reloadData];
} else {
@try {
[collectionView performBatchUpdates:^{
if ([removedPaths count] > 0) {
[collectionView deleteItemsAtIndexPaths:removedPaths];
}
if ([insertedPaths count] > 0) {
[collectionView insertItemsAtIndexPaths:insertedPaths];
}
if ([changedPaths count] > 0) {
[collectionView reloadItemsAtIndexPaths:changedPaths];
}
} completion:^(BOOL finished) {
if (_fetchResult.count == 0) {
MTLog(@"There is no photo in this album yet!!!");
[self.navigationController popViewControllerAnimated:YES];
}
}];
}
@catch (NSException *exception) {
[collectionView reloadData];
}
}
}
});
}
【讨论】: