Skip to content

Instantly share code, notes, and snippets.

@annidy
Last active December 22, 2015 17:08
Show Gist options
  • Save annidy/1574e747779a137445b7 to your computer and use it in GitHub Desktop.
Save annidy/1574e747779a137445b7 to your computer and use it in GitHub Desktop.
监视相册变化
//
// AssetSource.m
// CameraWathcher
//
// Created by FengXing on 13-9-9.
// Copyright (c) 2013年 FengXing. All rights reserved.
//
#import "AssetSource.h"
@interface AssetSource ()
@property ALAssetsLibrary *assetsLibrary;
@property NSMutableArray *assetsArray;
@property NSInteger assetCount;
@end
@implementation AssetSource
+ (id)sharedInstance
{
static AssetSource *ins = nil;
if (ins == nil) {
ins = [[AssetSource alloc] init];
ins.assetsArray = [[NSMutableArray alloc] init];
ins.maxTimeInterval = 30;
}
return ins;
}
- (void)watch
{
self.assetsLibrary = [[ALAssetsLibrary alloc] init];
ALAssetsLibrary *notificationSender = nil;
NSString *minimumSystemVersion = @"4.1";
NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
if ([systemVersion compare:minimumSystemVersion options:NSNumericSearch] != NSOrderedAscending)
notificationSender = self.assetsLibrary;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(assetsLibraryDidChange:)
name:ALAssetsLibraryChangedNotification object:notificationSender];
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self assetsLibraryDidChange:nil];
});
}
- (void)unwatch
{
if (self.assetsLibrary) {
[[NSNotificationCenter defaultCenter] removeObserver:self name:ALAssetsLibraryChangedNotification object:nil];
#if !__has_feature(objc_arc)
[self.assetsLibrary release];
#endif
}
}
- (void)assetsLibraryDidChange:(NSNotification *)notify
{
ALAssetsLibrary *assetLibrary = self.assetsLibrary;
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
*stop = YES;
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
if ([group numberOfAssets] <= self.assetCount) {
return;
} else {
self.assetCount = [group numberOfAssets];
}
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:self.assetCount-1]
options:0
usingBlock:
^(ALAsset *asset, NSUInteger index, BOOL *stopIt) {
if (asset) {
self.lastAsset = asset;
*stopIt = YES;
if ([self isTakenInTime:self.lastAsset]) {
[[NSNotificationCenter defaultCenter] postNotificationName:kAssetSourceLastTake object:self];
}
}
}];
}
}
failureBlock:^(NSError *error) {
NSLog(@"error enumerating AssetLibrary groups %@\n", error);
}];
}
- (BOOL)isTakenInTime:(ALAsset *)asset
{
NSDate *date = [asset valueForProperty:ALAssetPropertyDate];
if (date == nil) {
return NO;
}
return -[date timeIntervalSinceNow] < self.maxTimeInterval;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment