我使用UIImagePickerController选择图像并加载到我的UIImageView,但是我想保存用户选择并稍后加载它,我认为保存绝对路径到用户默认值但不能正常工作(
我如何保存路径//所有工作
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo: (NSDictionary *)info
{
[self.backgroundImage setImage:info[UIImagePickerControllerOriginalImage]];
NSURL* localUrl = (NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL];
//in localUrl I see: assets-library://asset/asset.JPG?id=B6C0A21C-07C3-493D-8B44-3BA4C9981C25&ext=JPG
NSUserDefaults *saves = [NSUserDefaults standardUserDefaults];
[saves setValue:[localUrl absoluteString] forKey:@"backimage"];
[saves synchronize];
[self dismissViewControllerAnimated:YES completion:nil];
}
我如何尝试加载://无法正常工作(
NSUserDefaults *saves = [NSUserDefaults standardUserDefaults];
if(![saves objectForKey:@"backimage"]){
[self.backgroundImage setImage:[UIImage imageNamed:@"gameBackiPhone"]];
}else{
NSURL *url = [NSURL URLWithString:[saves objectForKey:@"backimage"]];
//in url I see: assets-library://asset/asset.JPG?id=B6C0A21C-07C3-493D-8B44-3BA4C9981C25&ext=JPG
UIImage *bimage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:url]];
[self.backgroundImage setImage:bimage];
}
我怎么找不到。
答案 0 :(得分:1)
您无法使用资产URL直接加载图片,您需要使用ALAssetsLibrary
类来实现它。使用以下代码段使用资产网址加载图片。
// *** It will return Asset from URL passed, create Image from Asset and set into your `UIImageView` ***
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
if (iref) {
UIImage *largeimage = [UIImage imageWithCGImage:iref];
yourImageView.image = largeImage;
}
};
// *** If any error occurs while getting image from Asset Library following block will be invoked ***
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(@"Can't get image - %@",[myerror localizedDescription]);
};
// *** Set Asset URL to load Image (assets-library://asset/asset.JPG?id=B6C0A21C-07C3-493D-8B44-3BA4C9981C25&ext=JPG) ***
[NSURL *asseturl = [NSURL URLWithString:yourURL];
// *** Create ALAssetsLibrary Instance and load Image ***
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:asseturl
resultBlock:resultblock
failureBlock:failureblock];
不要忘记在项目中导入AssetsLibrary
框架。