如何使用ALAssetLibrary在相机胶卷中获取本地照片

时间:2012-06-19 03:15:16

标签: ios camera photo grand-central-dispatch alassetslibrary

ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
    [library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
                           usingBlock:libraryGroupsEnumeration 
                         failureBlock:failureblock];
ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result, NSUInteger index, BOOL *stop){
        if (result!=NULL) {

            if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {

                [self._dataArray addObject:result];
            }

        }
    };

ALAssetsLibraryGroupsEnumerationResultsBlock
    libraryGroupsEnumeration = ^(ALAssetsGroup* group, BOOL* stop){
        //within the group enumeration block.filter to enumerate just photos.
        [group setAssetsFilter:[ALAssetsFilter allPhotos]];
        if (group!=nil) {
            NSString *g=[NSString stringWithFormat:@"%@",group];
            NSLog(@"gg:%@",g);//gg:ALAssetsGroup - Name:Camera Roll, Type:Saved Photos, Assets count:71
            [group enumerateAssetsUsingBlock:groupEnumerAtion];
        }
        else {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [self saveToDB:self._dataArray];

            });
        }

    };

假设我的相机胶卷有100张照片,我希望先前30张保存到我的数据库。但在上面的代码中,我必须等待100个结果fisishing.30后写入数据库,继续获得另外30个直到结束。 因为获得100张甚至更多照片会延迟我的UI刷新。看起来不舒服。 非常感谢!

我应该写什么。?

2 个答案:

答案 0 :(得分:0)

您应该尝试在后台线程上保存到数据库,并让CoreData(假设您使用CoreData)通过处理NSManagedObjectContextDidSaveNotification更新主线程上的NSManagedObjectContext。

30张照片后你仍然可以保存,这可能会减轻一些I / O压力,但你必须测试性能。

答案 1 :(得分:0)

试试这个

if (result!=NULL) {

    if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])         {

          [self._dataArray addObject:result];

            if([self._dataArray count] == 30){

               dispatch_async(dispatch_get_global_queue(0, 0), ^{

                 NSArray *array = [[NSArray alloc] initWithArray:self._dataArray]; //please change the array declaration to top of this method. Because the Block will not allow to do it here.               
                 [self._dataArray removeAllObjects];
                 [self saveToDB:array];
                 //array release,if not using ARC

           });
       }
    }

}

if (group!=nil) {

            [group enumerateAssetsUsingBlock:groupEnumerAtion];
        }
        else if([self._dataArray count] > 0) {

              dispatch_async(dispatch_get_global_queue(0, 0), ^{

                    [self saveToDB:self._dataArray];

            });
        }