【问题标题】:UIImagePickerController not picking the imageUIImagePickerController 没有选择图像
【发布时间】:2019-06-11 18:44:12
【问题描述】:

我正在尝试制作一个允许使用 ImagePickerController 向其添加图像和名称并通过 AlertController TextField 更改其名称的 TableView 应用程序

问题是 ImagePicker 没有拾取图像并且调试控制台上没有显示错误。

当我单击图像来选择它时,什么也没有发生。

class ViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    var photos = [Photo]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "Snapshots"
        navigationController?.navigationBar.prefersLargeTitles = true

        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPhoto))

        let defaults = UserDefaults.standard

        if let savedPhotos = defaults.object(forKey: "photos") as? Data {
            let jsonDecoder = JSONDecoder()
            do {
                photos = try jsonDecoder.decode([Photo].self, from: savedPhotos)
            } catch {
                print("Failed to load photos.")
            }
        }

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return photos.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "Photo", for: indexPath) as? PhotoCell else {
            fatalError("Could not load the Photo Cell")
        }
        let photo = photos[indexPath.row]
        cell.textLabel?.text = photo.name
        let path = getDocumentsDirectory().appendingPathComponent(photo.image)
        cell.imageView?.image = UIImage(contentsOfFile: path.path)

        return cell
    }

    @objc func addPhoto() {
        let picker = UIImagePickerController()
        picker.isEditing = true
        picker.delegate = self
        present(picker, animated: true)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let image = info[.editedImage] as? UIImage else { return }

        let imageName = UUID().uuidString
        let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)

        if let jpegData = image.jpegData(compressionQuality: 0.8) {
            try? jpegData.write(to: imagePath)
        }

        let photo = Photo(name: "New Image", image: imageName)
        photos.append(photo)
        save()
        tableView.reloadData()

        dismiss(animated: true)

    }

    func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

            let photo = photos[indexPath.row]

            let ac = UIAlertController(title: "What you want to do with Image?", message: nil, preferredStyle: .alert)

            ac.addTextField()

            ac.addAction(UIAlertAction(title: "Rename", style: .default) {
                [weak self, weak ac] _ in
                guard let newName = ac?.textFields?[0].text else { return }
                photo.name = newName
                self?.save()
                self?.tableView.reloadData()
            })

            ac.addAction(UIAlertAction(title: "Delete", style: .destructive) {
                [weak self] _ in
                self?.photos.remove(at: indexPath.row)
                self?.tableView.reloadData()
            })

            ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

            ac.addAction(UIAlertAction(title: "Open", style: .default) {
                [weak self] _ in
                if let vc = self?.storyboard?.instantiateViewController(withIdentifier: "PhotoView") as? DetailViewController {
                    vc.selectedImage = photo.name
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
            })

            present(ac, animated: true)

    }

    func save() {
        let jsonEncoder = JSONEncoder()
        if let savedData = try? jsonEncoder.encode(photos) {
            let defaults = UserDefaults.standard
            defaults.set(savedData, forKey: "photos")
        } else {
            print("Failed to save photos.")
        }
    }

}

【问题讨论】:

  • “ImagePicker 没有拾取图像”是什么意思?是否显示图像选择器?选择图像时是否调用图像选择器委托?

标签: ios swift swift4 uiimagepickercontroller


【解决方案1】:

我实际上把你的代码压缩了很多以在本地测试并在这里发现了一个可能的问题:

guard let image = info[.editedImage] as? UIImage else { return }

如果您的用户尚未编辑照片,则返回开始,不会发生任何进一步的事情。

但是,如果我像这样将其更改为.originalImage,那么只需选择一个图像即可继续:

guard let image = info[.originalImage] as? UIImage else { return }

话虽如此,您可能需要考虑使用 switch 语句或一些 if/else 来根据适合您应用的任何内容来促进不同类型的图像。

【讨论】:

    【解决方案2】:

    您是否在 info.plist 文件中添加了照片库使用权限?如果您还没有,请在 info.plist 中添加“隐私 - 照片库使用说明”。

    【讨论】:

    • 没有用,那为什么要加
    • ImagePickerController 从您的照片库中挑选图像。要访问照片库,您需要获得许可。
    • @RajatSharma 您不需要此隐私设置即可使用UIImagePickerController
    • @RajatSharma 如果你想要的只是.originalImage,你确实不需要需要用户许可。 stackoverflow.com/a/48413456/341994
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多