使用相册、相机
2017-05-10 本文已影响0人
一蓑丨烟雨
首先需要在info.plist文件中添加以下键值对:
<key>NSCameraUsageDescription</key>
<string>使用相机</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>使用相册</string>
剩下的废话不多说,直接上代码:
#pragma mark -- 点击添加用户的头像
-(void)addUserHeadImg:(UIButton *)btn{
if (_user) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
__weak typeof(self) weakSelf = self;
[alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
[weakSelf showImagePickerVCWithType:UIImagePickerControllerSourceTypeCamera];
}
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[weakSelf showImagePickerVCWithType:UIImagePickerControllerSourceTypePhotoLibrary];
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
}
}
//拍照
-(void)showImagePickerVCWithType:(UIImagePickerControllerSourceType)type{
//创建pickerVC
UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
//设置图片来源,可以使相机/相册
pickerVC.sourceType = type;
pickerVC.allowsEditing = YES;
pickerVC.delegate = self;
//弹出pickerVC
[self presentViewController:pickerVC animated:YES completion:nil];
}
#pragma mark -- 获取用户选择的图片代理
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
UIImage *img = info[@"UIImagePickerControllerEditedImage"];
[_headImgV setImage:img forState:UIControlStateNormal];
[_headImgV setImageEdgeInsets:UIEdgeInsetsZero];
[self upDataHeadImageBox:img];
[picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark -- 把选择的图片存到本地
-(void)upDataHeadImageBox:(UIImage *)img{
//更新沙盒
NSMutableData *mutableData = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mutableData];
[archiver encodeObject:img forKey:kHeadKey];
[archiver finishEncoding];
[mutableData writeToFile:kFilePath atomically:YES];
}