在我的应用程序中,我从拾取器中获取图像,然后尝试在单独的视图中显示它。
在我的MainViewController.m中我有
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[picker dismissViewControllerAnimated:YES completion:^ {
self.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:UIImagePNGRepresentation(self.image) forKey:@"imageKey"];
[defaults synchronize];
PublishViewController *publish = [self.storyboard instantiateViewControllerWithIdentifier:@"Publish"];
[self presentViewController:publish animated:YES completion:nil];
}];
}
然后我尝试在PublishViewController.m中检索图像
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSData *imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"imageKey"];
UIImage *userImage = [UIImage imageWithData:imageData];
self.image = [[UIImageView alloc] initWithImage:userImage];
}
虽然图像没有显示。有什么理由吗?
答案 0 :(得分:0)
也许在-viewDidLoad
中的完成块之前调用PublishViewController.m中的dismissViewControllerAnimated:completion:
并且NSData尚未保存在NSUserDefaults中。
您可以将代码加载到self.image
中的PublishViewController.m中加载-ViewDidAppear
现在我说我同意评论者认为NSUserDefaults可能不是存储图像数据的最佳位置。
答案 1 :(得分:0)
您最好使用NSUserDefaults
来保存图片,而不是使用NSFileManager
。
在MainViewController.m
的pickerController委托方法中,放置以下代码 -
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
[self dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
//This code will save your image so you can retrieve it anywhere else within the app.
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentDirectory stringByAppendingPathComponent:@"yourImageName.jpg"];
[manager createFileAtPath:fullPath contents:imageData attributes:nil];
}
您可以将图像名称保存为您喜欢的任何内容
然后在viewDidLoad
PublishViewController.m
的{{1}}内放置此代码以检索图片 -
-(void)viewDidLoad{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:@"yourImageName.jpg"];
UIImage *retrievedImage = [UIImage imageWithContentsOfFile:fullPath];
self.yourImageView.image = retrievedImage;
}
在此UIImageView
PublishViewController
的视图控制器上放置yourImageView
,我已将其称为{{1}}。
这适用于您正在寻找的内容,希望它有所帮助。
谢谢,吉姆。