【发布时间】:2015-09-23 17:06:49
【问题描述】:
在我的应用程序中,我必须实现保存图像功能。我已经管理过这样的保存:
UIImage *image = [UIImage imageNamed:actualBackground];
UIImageWriteToSavedPhotosAlbum(
image, self,
@selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:),
nil);
/* ... */
- (void)thisImage:(UIImage *)image
hasBeenSavedInPhotoAlbumWithError:(NSError *)error
usingContextInfo:(void *)ctxInfo {
if (!error){
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
[self presentViewController:picker animated:YES completion:nil];
}
}
不幸的是,我必须检查文件是否已经存在以防止多余的保存。这也是必要的,因为多次保存同一个图像不会覆盖一个文件,但它会创建它的副本...
你知道如何解决这个问题吗?
解决方案:
根据Shravya Boggarapu 的回答,我将assetUrl 存储在我的NSUserDefaults 中。完整代码:
- (IBAction)onDownloadClick:(UIButton *)sender {
UIImage *image = [UIImage imageNamed:actualBackground];
NSString *key = [NSString stringWithFormat:@"assetsUrl %@", actualBackground];
NSString *savedValue =
[[NSUserDefaults standardUserDefaults] stringForKey:key];
NSURL *url = [NSURL URLWithString:savedValue];
if (url != nil) {
PHFetchResult *fetch =
[PHAsset fetchAssetsWithALAssetURLs:[NSArray arrayWithObject:url]
options:nil];
if ([fetch count]) {
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:nil
message:NSLocalizedString(@"Already downloaded", nil)
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[myAlert show];
return;
}
}
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library
writeImageToSavedPhotosAlbum:image.CGImage
orientation:(ALAssetOrientation)image.imageOrientation
completionBlock:^(NSURL *assetURL, NSError *error) {
[library assetForURL:assetURL
resultBlock:^(ALAsset *asset) {
NSLog(@"assetURL %@", assetURL);
NSString *ass = [assetURL absoluteString];
[[NSUserDefaults standardUserDefaults]
setObject:ass
forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:nil
message:NSLocalizedString(
@"Image downloaded", nil)
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[myAlert show];
}
failureBlock:^(NSError *error){
}];
}];
}
希望它会帮助别人。
【问题讨论】:
-
如何在 Swift 中做到这一点?
标签: ios objective-c image gallery