如何在UIAlertController中添加图片选择器,实现用户相册上传图片功能
功能实现解答
是否需要使用数据库/CoreData?
不需要,除非你需要应用重启后仍然保留已添加的设备数据和对应配图:
- 如果仅需要当前应用运行时临时存储展示,只需要把选中的图片存在内存的设备模型数组中即可,无需持久化组件
- 如果后续需要持久化存储,也可以选择更轻量的方案:把图片写入沙盒Documents目录,将图片存储路径和设备名称、描述一起存在plist或UserDefaults中,不需要接入CoreData
具体代码实现步骤
1. 先加相册访问权限
在项目的Info.plist中添加权限声明:
key为NSPhotoLibraryUsageDescription,value填写向用户说明权限用途的文字,比如「需要访问相册以选择智能设备配图」
2. 声明临时存储选中图片的变量
在当前ViewController类中添加变量:
// 临时存储用户选中的设备配图 var selectedDeviceImage: UIImage?
3. 修改现有UIAlertController代码
UIAlertController本身不支持直接嵌入图片选择器,你可以新增一个按钮触发图片选择弹窗,这里用iOS14+推荐的PHPicker实现(不需要申请全相册权限,用户可以只给单张图片权限):
首先让你的ViewController遵守PHPickerViewControllerDelegate协议,然后修改你的@IBAction代码:
@IBAction func refreash(_ sender: AnyObject) { // 每次弹窗先重置上次选中的图片 selectedDeviceImage = nil let alert = UIAlertController(title: "Add Smart Device", message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addTextField(configurationHandler: { textField in textField.placeholder = "Enter Name of the Smart Device Here" }) alert.addTextField(configurationHandler: { textField in textField.placeholder = "Enter Desc of the Smart Device Here" }) // 新增选择图片的按钮 alert.addAction(UIAlertAction(title: "从相册选择配图", style: .default, handler: { _ in var config = PHPickerConfiguration() config.filter = .images config.selectionLimit = 1 let picker = PHPickerViewController(configuration: config) picker.delegate = self self.present(picker, animated: true) })) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in guard let name = alert.textFields?.first?.text, let desc = alert.textFields?[1].text else { return } // 如果用户没选图就用默认图 let finalImage = self.selectedDeviceImage ?? UIImage(named: "robot.jpg") // 注意:原来的addSmartDevice方法的image参数如果是字符串类型,需要你自己调整成支持UIImage,或者把图片存到沙盒后传路径字符串 self.mySmartDeviceList.addSmartDevice(name: name, desc: desc, image: finalImage) let indexPath = IndexPath (row: self.mySmartDeviceList.getCount() - 1, section: 0) self.cityTable.beginUpdates() self.cityTable.insertRows(at: [indexPath], with: .automatic) self.cityTable.endUpdates() })) self.present(alert, animated: true) } // MARK: - PHPickerViewControllerDelegate extension YourViewControllerClassName: PHPickerViewControllerDelegate { func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { picker.dismiss(animated: true) guard let result = results.first else { return } if result.itemProvider.canLoadObject(ofClass: UIImage.self) { result.itemProvider.loadObject(ofClass: UIImage.self) { [weak self] obj, error in DispatchQueue.main.async { guard let self = self, let image = obj as? UIImage, error == nil else { return } self.selectedDeviceImage = image } } } } }
注意:把代码里的
YourViewControllerClassName替换成你当前的ViewController类名。如果需要兼容iOS14以下版本,把PHPicker替换成UIImagePickerController即可。
内容的提问来源于stack exchange,提问作者zzzz
相关产品推荐
相关产品推荐

