使用Photo Framework 框架中的 PHPhotoLibrary 操作
/**
* 将网络保存到本地相册, 并存入缓存数组以便使用
* imageUrl: 网络图片URL
*/
- (void)saveNetworkImageToAlbum:(NSString *)imageUrl{
//判断本地是否存在相同图片的标识
NSString *localIdentifier = [[NSUserDefaults standardUserDefaults] objectForKey:imageUrl];
NSURL *fileURL = [NSURL URLWithString:imageUrl];
NSData *imageData = [NSData dataWithContentsOfURL:fileURL];
UIImage *image = [UIImage imageWithData:imageData];
if (localIdentifier == nil) {
[self execSavePhoto:image withUrl:imageUrl];
}else {
//根据本地图片的唯一标识符(localIdentifier),找到asset
PHAsset * asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[localIdentifier] options:nil].firstObject;
if (asset == nil) {
[self execSavePhoto:image withUrl:imageUrl];
}else {
[_selectedPhotos addObject:image];
[_selectedAssets addObject:asset];
}
}
}
/**
* 调用PHPhotoLibrary库 保存图片
*/
- (void)execSavePhoto:(UIImage *)image withUrl:(NSString *)urlStr{
if (iOS8Later){
NSError *err = nil;
__block PHAsset *phAsset = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
//写入图片到相册
PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
NSString *localIdentifier = req.placeholderForCreatedAsset.localIdentifier;
phAsset = [PHAsset fetchAssetsWithLocalIdentifiers:@[localIdentifier] options:nil].firstObject;
} error:&err];
if (err) {
NSLog(@"保存照片出错:%@",err.localizedDescription);
}else {
if (phAsset != nil) {
//将存在本地的图片的唯一标识符,存入plist,便于判断本地是否存在该图片
//key: 表示唯一的imageUrl value: 图片的唯一标识符(localIdentifier)
[[NSUserDefaults standardUserDefaults] setObject:phAsset.localIdentifier forKey:urlStr];
[[NSUserDefaults standardUserDefaults] synchronize];
[_selectedPhotos addObject:image];
[_selectedAssets addObject:phAsset];
}
}
}
}