我正在尝试制作一个TableView App,该App允许使用ImagePickerController向其中添加图像和名称,并通过AlertController TextField更改其名称
问题是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.")
}
}
}
答案 0 :(得分:0)
我实际上将您的代码压缩了很多,以便在本地进行测试,并在此处发现一个可能的问题:
guard let image = info[.editedImage] as? UIImage else { return }
如果您的用户尚未编辑照片,则返回提示,并且不再发生任何事情。
但是,如果我这样将其更改为.originalImage
,则只需选择一张图像即可继续进行操作:
guard let image = info[.originalImage] as? UIImage else { return }
话虽如此,您可能要考虑使用switch语句,或者使用if / else语句来根据适合您的应用的各种类型来提供不同类型的图像。
答案 1 :(得分:-1)
您是否已在info.plist文件中添加了“照片库使用”权限?如果没有,请在info.plist中添加“隐私-照片库使用说明”。