iOS learning - call mobile phone album, expand: identify the QR code of the album

Preface: I believe everyone knows that most apps have my module, and my module basically has information such as the user's avatar, and the avatar can be changed. So today I will give you a brief introduction on how to call the system camera to take pictures or obtain photos from the album in iOS development. To get the system camera or photo album, we need to use the UIImagePickerController class. Let's take a look at how to achieve it:

First, you need to follow the two protocols of the UIImagePickerController delegate: <UIImagePickerControllerDelegate, UINavigationControllerDelegate>. Why two agreements? You press the command key and click on the delegate of UIImagePickerController, and you will find that the delegate actually complies with two protocols.

#import "HeaderPhotoViewController.h"

@interface HeaderPhotoViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIImageView * imageView;
@end

@implementation HeaderPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设置头像";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setNavigation];
    [self addSubviews];
    [self makeConstraintsForUI];
}

#pragma mark - set navigation

- (void)setNavigation {
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(selectPhoto:)];
}

#pragma mark - navitation item action

- (void)selectPhoto:(UIBarButtonItem *)itemCamera {

    //创建UIImagePickerController对象,并设置代理和可编辑
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.editing = YES;
    imagePicker.delegate = self;
    //设置是否可编辑
    imagePicker.allowsEditing = YES;

    //创建sheet提示框,提示选择相机还是相册
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"请选择打开方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    //相机选项
    UIAlertAction * camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        //选择相机时,设置UIImagePickerController对象相关属性
        imagePicker.sourceType =  UIImagePickerControllerSourceTypeCamera;
        imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        //跳转到UIImagePickerController控制器弹出相机
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];

    //相册选项
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        //选择相册时,设置UIImagePickerController对象相关属性
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //跳转到UIImagePickerController控制器弹出相册
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];

    //取消按钮
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }];

    //添加各个按钮事件
    [alert addAction:camera];
    [alert addAction:photo];
    [alert addAction:cancel];

    //弹出sheet提示框
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - add subviews

- (void)addSubviews {
    
    [self.view addSubview:self.imageView];
}

#pragma mark - make constraints

- (void)makeConstraintsForUI {
    
    __weak typeof(self)weakSelf = self;
    
    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(Screen_Width, Screen_Width));
        make.centerX.mas_equalTo(weakSelf.view.mas_centerX);
        make.centerY.mas_equalTo(weakSelf.view.mas_centerY);
    }];
}

#pragma mark - imagePickerController delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    //获取到的图片
    UIImage * image = [info valueForKey:UIImagePickerControllerEditedImage];
    _imageView.image = image;
}

#pragma mark - setter and getter

- (UIImageView *)imageView {
    
    if (!_imageView) {
        
        _imageView = [[UIImageView alloc] init];
        _imageView.backgroundColor = [UIColor greenColor];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _imageView;
}

@end

OK! All the codes of the demo have been presented to everyone. The last step is to configure the plist file. Don’t forget this, or it will collapse. Add the field Privacy - Camera Usage Description for calling the camera and the field for calling the album: Privacy - Photo Library Usage Description in the plist file. Everything is ready, the only thing missing is an Apple mobile phone for testing. The camera test needs to be tested with a real device.

Finally, I hope to help ape friends in need, and hope that we, who are also programmers, can learn and progress together, and go further and further on the road of development! Thanks!

Expansion: If you want to recognize the QR code of the selected picture, you need to modify it in the agent. The specific code is as follows

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    //获取到的图片
    UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
    // 2、创建 CIImage
    CIImage *ciimage = [[CIImage alloc] initWithImage:image];
    // 3、识别精度
    NSDictionary *options = @{CIDetectorAccuracy: CIDetectorAccuracyHigh};
    // 4、创建识别器
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:options];
    
    NSArray *features = [detector featuresInImage:ciimage];
    
    NSString *message = nil;
    for (CIFeature *item in features) {
        if ([item isKindOfClass:[CIQRCodeFeature class]]) {
            message = [(CIQRCodeFeature *)item messageString];
            NSLog(@"message = %@", message);
            break;
        }
    }
}

Set whether to edit pictures

BOOL allowsEditing

Set whether to jump to the edit mode for picture cropping after taking a photo or selecting a photo in the album, that is, whether to allow editing

Only works when showsCameraControls=Yes.

[imagePicker setAllowsEditing:YES]; 

To cancel editing, set it to NO, and change the type of the obtained image to UIImagePickerControllerOriginalImage

[imagePicker setAllowsEditing:NO]; 

UIImage * image = [info valueForKey:UIImagePickerControllerOriginalImage];

Reference: iOS Development - Call System Camera and Album to Get Photos - Short Book ios Basics (1) - UIImagePickerController Class_A Program Yuan0915's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/qq_43441647/article/details/130504701