当我尝试从我的代码加载相机时,相机预览为黑色。如果我等待10-20秒,它将显示真实的相机预览。我发现了几个问题,其中一些问题表明在后台运行其他代码应该是这个问题的原因。但是我没有在后台运行任何代码。 我该如何解决这个问题?
这是我运行相机的代码
UIImagePickerController *photoPicker = [[UIImagePickerController alloc] init];
photoPicker.delegate = self;
photoPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:photoPicker animated:YES completion:NULL];
答案 0 :(得分:21)
大约5个月前,我的团队在iOS7中发现了UIImageViewController的内存泄漏。每个实例化都以指数方式减慢app(即第一个alloc-init延迟1秒,第二个延迟2秒,第三个延迟5秒)。最终,我们有30-60次延迟(类似于您所遇到的情况)。
我们通过继承UIImagePickerController并使其成为Singleton解决了这个问题。这样它只被初始化一次。现在我们的延迟很小,我们避免泄漏。如果子类化不是一个选项,请在viewController中尝试一个class属性,然后像这样延迟加载它。
-(UIImagePickerController *)imagePicker{
if(!_imagePicker){
_imagePicker = [[UIImagePickerController alloc]init];
_imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
return _imagePicker;
}
然后你可以稍后再称它为:
[self presentViewController:self.imagePicker animated:YES completion:nil];
答案 1 :(得分:2)
如果有这个问题 - 如果主调度线程上正在运行某些东西会发生这种情况 - 您是否有机会调整图像大小?
它将预览放到主线程上,如果有什么东西使用它,你会得到一个黑屏。这是一个错误,解决方法是接管主线程或禁用照片选择器直到队列空闲
答案 2 :(得分:-1)
这应该适合你:
- (void)cameraViewPickerController:(UIImagePickerController *)picker
{
[self startCameraControllerFromViewController: picker
usingDelegate: self];
}
- (BOOL) startCameraControllerFromViewController: (UIViewController*) controller
usingDelegate: (id <UIImagePickerControllerDelegate,
UINavigationControllerDelegate>) delegate {
if (([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeCamera] == NO)
|| (delegate == nil)
|| (controller == nil))
return NO;
UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
// Displays a control that allows the user to choose movie capture
cameraUI.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeImage, (NSString *) kUTTypeMovie,nil];
// Hides the controls for moving & scaling pictures, or for
// trimming movies. To instead show the controls, use YES.
cameraUI.allowsEditing = NO;
cameraUI.delegate = delegate;
[controller presentViewController:cameraUI animated:YES completion:nil];
return YES;
}