UIImagePickerController学习记录

本文记录了使用UIImagePickerController进行图像获取时遇到的问题与解决方案,包括初始化时的卡顿问题,检查相册可用性的方法,以及相关协议的使用。通过讨论UINavigationControllerDelegate的作用,提供参考文章以帮助理解并解决实际开发中的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

  • 为了写图像识别,需要能通过相册和照相机获取照片,因此学习一下UIImagePickerController

关于UINavigationControllerDelegate

  • 在使用UIImagePickerController时需要遵守<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

  • 原因要看一下UIImagePickerController的定义

  @interface UIImagePickerController : UINavigationController <NSCoding>
  
  @property(nullable,nonatomic,weak)      id <UINavigationControllerDelegate, UIImagePickerControllerDelegate> delegate;
  • UIImagePickerController本身就是继承于UINavigationController的
  • 同时delegate的申明里也写清楚了要遵守这两个协议
  • 猜测可能是因为 UIImagePickerController本身就设计了工具栏的变化

初始化UIImagePickerController卡顿

  • 执行self.imagePickerController = [[UIImagePickerController alloc] init];初始化时,模拟机直接出现了3,4秒的卡顿
  • 在stack overflow上同样有人遇到这个问题UIImagePickerController really slow when calling alloc init
  • 高赞回答说只要demo不是debug model也就是不是通过Xcode运行就没事,经过测试,这是真的
  • 剩下的就很直接的异步就完事了
  • 所以最后觉得这一块改不改无所谓

检验相册是否可用

+ (BOOL)isSourceTypeAvailable:(UIImagePickerControllerSourceType)sourceType;                 // returns YES if source is available (i.e. camera present)

if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
	return;
}
//判断打开相册是否可用

返回NO的几种可能性

  • 模拟机上没有照相机可以开启,需要使用真机
  • 在Info.plist里没有增加key
  • 没有锁定竖屏

UIImagePickerControllerDelegate

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    //销毁控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
    //设置图片
    self.testImageView = [[UIImageView alloc] init];
    _testImageView.image = info[UIImagePickerControllerOriginalImage];
    NSLog(@"%@FAILQSTZZ", _testImageView.image);
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    NSLog(@"FAILQSTSD");
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

参考文章

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值