如何在iOS中的两个日期范围内从照片库中获取图像? [英] How to fetch images from photo library within range of two dates in iOS?

查看:99
本文介绍了如何在iOS中的两个日期范围内从照片库中获取图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在照片库的两个日期范围内获取图片。

I am try to fetch images within range of two dates from the photo library.

首先,我在字典表格中逐个获取照片库图片的信息,并使用密钥选择每个图像日期,并使用if条件将该日期与两个日期进行比较。

Firstly, I am getting info of the photo library images one by one in the dictionary form and picking every image date by using key and comparing that date with two dates by using if condition.

如果该图像的日期位于两个日期之间,我将该图像插入数组。

If that image's date lies between the two dates, I insert that image into array.

我正在将图像保存在数组中,因为我想在一个数组中显示它们集合视图。

I am Saving images in array because I would like to show them in a collection view.

当它在模拟器上工作时,它不能在真实设备上工作,因为内存问题。

While it is working on simulator, it is not working on real device because of memory issues.

我认为真实设备照片库中有大量图像,这就是为什么会出现内存问题。

I think there are bunch of images in the real device photo library that's why am getting memory issues.

如何解决这个问题?

推荐答案

按照我们的要求在您同意切换到Photos Framework而不是Assets Library的评论中的对话,而不是将图像保存到您的阵列,将PHAsset的本地标识符保存到您的阵列。

As per our conversation in comments in which you agreed to switch to Photos Framework instead of Assets Library, Rather than saving the images to your array, save the PHAsset's local identifier to your array.

要按日期获取图像,请先创建一个实用程序方法来创建日期,为了可重用性:

To get Images by Date, first create a utility method to create date, for reusability's sake:

-(NSDate*) getDateForDay:(NSInteger) day andMonth:(NSInteger) month andYear:(NSInteger) year{
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:day];
    [comps setMonth:month];
    [comps setYear:year];
    NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:comps];
    return date;
} 

您可以像这样创建startDate和endDate:

You can create startDate and endDate from it like this:

NSDate *startDate = [self getDateForDay:11 andMonth:10 andYear:2015];
NSDate *endDate = [self getDateForDay:15 andMonth:8 andYear:2016];

现在你需要从这个范围之间的照片库中获取FetchResults。使用此方法:

Now you need to get the FetchResults from Photo Library which exist between this range. Use this method for that:

-(PHFetchResult*) getAssetsFromLibraryWithStartDate:(NSDate *)startDate andEndDate:(NSDate*) endDate
{
    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
    fetchOptions.predicate = [NSPredicate predicateWithFormat:@"creationDate > %@ AND creationDate < %@",startDate ,endDate];
    PHFetchResult *allPhotos = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions]; 
    return allPhotos;
}

现在你得到 PHFetchResults 此日期范围内存在的所有照片。现在要提取本地标识符的数据数组,您可以使用以下方法:

Now you get the PHFetchResults of all the Photos which exist within this date range. Now to extract your Data Array of local identifiers, you can use this method:

-(NSMutableArray *) getAssetIdentifiersForFetchResults:(PHFetchResult *) result{

    NSMutableArray *identifierArray = [[NSMutableArray alloc] init];
    for(PHAsset *asset in result){
        NSString *identifierString = asset.localIdentifier;
        [identifierArray addObject:identifierString];
    }
    return identifierArray;
}



添加在需要时获取/利用个别资产的方法



现在,图像需要 PHAsset 。你可以像这样使用LocalIdentifier来获得 PHAsset

Add Methods to fetch/utilize the individual assets when you need them

Now, you will need the PHAsset for the image. You can use the LocalIdentifier like this to get PHAsset:

-(void) getPHAssetWithIdentifier:(NSString *) localIdentifier andSuccessBlock:(void (^)(id asset))successBlock failure:(void (^)(NSError *))failureBlock{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSArray *identifiers = [[NSArray alloc] initWithObjects:localIdentifier, nil];
        PHFetchResult *savedAssets = [PHAsset fetchAssetsWithLocalIdentifiers:identifiers options:nil];
        if(savedAssets.count>0)
        {
            successBlock(savedAssets[0]);
        }
        else
        {
            NSError *error;
            failureBlock(error);
        }
    });
}

然后使用此 PHAsset ,您可以获得所需大小的图像(尝试尽可能减少内存使用量):

Then using this PHAsset, you can get the image for your required size (Try to keep it as minimum as possible to minimize memory usage):

-(void) getImageForAsset: (PHAsset *) asset andTargetSize: (CGSize) targetSize andSuccessBlock:(void (^)(UIImage * photoObj))successBlock {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHImageRequestOptions *requestOptions;

        requestOptions = [[PHImageRequestOptions alloc] init];
        requestOptions.resizeMode   = PHImageRequestOptionsResizeModeFast;
        requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
        requestOptions.synchronous = true;
        PHImageManager *manager = [PHImageManager defaultManager];
        [manager requestImageForAsset:asset
                           targetSize:targetSize
                          contentMode:PHImageContentModeDefault
                              options:requestOptions
                        resultHandler:^void(UIImage *image, NSDictionary *info) {
                            @autoreleasepool {

                                if(image!=nil){
                                    successBlock(image);
                                }
                            }
                        }];
    });

}

但不要直接调用这些方法来获取所有你想要的图像。

But don't call these method directly to get all the images you desire.

相反,请在 cellForItemAtIndexPath 方法中调用这些方法,如:

Instead, call these methods in your cellForItemAtIndexPath method like:

 //Show spinner
[self getPHAssetWithIdentifier:yourLocalIdentifierAtIndexPath andSuccessBlock:^(id assetObj) {
        PHAsset *asset = (PHAsset*)assetObj;
        [self getImageForAsset:asset andTargetSize:yourTargetCGSize andSuccessBlock:^(UIImage *photoObj) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //Update UI of cell
                //Hide spinner
                cell.imgViewBg.image = photoObj;
            });
        }];
    } failure:^(NSError *err) {
       //Some error occurred in fetching the image
    }];



结论



所以总结:

Conclusion

So in conclusion:


  1. 您可以通过仅获取可见单元格的图像而不是获取整个图像来处理内存问题。

  2. 您可以通过在后台线程上获取图像来优化性能。

如果你想要将您的所有资产一起反正,你可以得到它使用 fetchAssetCollectionWithLocalIdentifiers :方法虽然我会建议反对它。

If you want to get all your assets together anyways, you can get it using fetchAssetCollectionWithLocalIdentifiers: method though I will recommend against it.

如果您有任何疑问或有任何其他反馈,请发表评论。

Please drop a comment if you have any questions or if you have any other feedback.

致Lyndsey Scott用于将谓词设置为PHFetchResult请求在她的答案中的两个日期之间获取图像< href =https://stackoverflow.com/a/35003679/4029561>这里

这篇关于如何在iOS中的两个日期范围内从照片库中获取图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆