最近处理了一个关于默认横屏调用系统相册/相机莫名闪退的bug,排除了权限配置问题之后 ,很大的原因是因为横竖屏切换的问题,有时候不闪退,但是相机只出现一半的情况,很是诡异,废话不多说,直接上代码
1.相机
在判断完APP相机权限为开启之后,调用系统打开相机 方法 ,在此之前发送一个通知(目的在后面)
NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
[dic setObject:@"1" forKey:@"deviceOrientation"];//允许竖屏
[[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeDevicesOrientation" object:nil userInfo:dic];
UIImagePickerController * picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.delegate= weakSelf;
picker.allowsEditing=NO;
[weakSelfpresentViewController:picker animated:YES completion:nil];
2.在appdelegate 的 didFinishLaunchingWithOptions 方法 里面创建一个监听者 并 实现监听通知的方法
@property(nonatomic,assign)NSUInteger currentOrientation;
//创建一个接收横竖转向的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangeDevicesOrientation:) name:@"ChangeDevicesOrientation" object:nil];
-(void)ChangeDevicesOrientation:(NSNotification*)noInfo
{
NSSLog(@"输出一看传递过来的信息:%@",noInfo.userInfo);
//UIImagePickerController
if ([[noInfo.userInfo objectForKey:@"deviceOrientation"] intValue]==1)
{
self.currentOrientation=UIInterfaceOrientationMaskPortrait; //竖屏
}
else
{
self.currentOrientation=UIInterfaceOrientationMaskLandscapeRight;//home键在右侧的横屏
}
}
//supportedInterfaceOrientationsForWindow这个方法就是改变当前界面横竖状态的方法,这个方法在每个界面加载的时候都会调用一次可以在方法里加入输出查看当前界面的类型.
- (UIInterfaceOrientationMask)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
{
return self.currentOrientation;
}
3.同样需要在相册的点击方法里面也需要发送通知,
NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
[dicsetObject:@"1" forKey:@"deviceOrientation"];//允许竖屏
[[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeDevicesOrientation" object:nil userInfo:dic];
UIImagePickerController * picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerCameraCaptureModePhoto;
picker.delegate=self;
picker.allowsEditing=NO;
[self presentViewController:picker animated:YES completion:nil];
4.在点击了相机/相册的取消按钮之后需要把状态改变回来,同样是发送通知改变
-(void)imagePickerControllerDidCancel:(UIImagePickerController*)picker
{
NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
[dicsetObject:@"0" forKey:@"deviceOrientation"];//不允许竖屏
[[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeDevicesOrientation" object:nil userInfo:dic];
[pickerdismissViewControllerAnimated:YES completion:nil];
}
5.在相机/相册的代理方法里面也需要发送通知改变为原来的横竖状态
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
[dicsetObject:@"0" forKey:@"deviceOrientation"];//不允许竖屏
[[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeDevicesOrientation" object:nil userInfo:dic];
........
}