6.5. Using Gallery: PHPicker
//
// AddExpenseViewController.swift
// App6
//
// Created by Sakib Miazi on 5/18/23.
//
import UIKit
import PhotosUI //MARK: importing the library to use PHPicker...
class AddExpenseViewController: UIViewController {
//codes omitted...
//MARK: variable to store the picked Image...
var pickedImage:UIImage?
//Codes omitted...
override func viewDidLoad() {
super.viewDidLoad()
//codes omitted...
//MARK: adding menu to buttonTakePhoto...
addExpenseScreen.buttonTakePhoto.menu = getMenuImagePicker()
//codes omitted...
}
//codes omitted...
func getMenuImagePicker() -> UIMenu{
var menuItems = [
UIAction(title: "Camera",handler: {(_) in
self.pickUsingCamera()
}),
UIAction(title: "Gallery",handler: {(_) in
self.pickPhotoFromGallery()
})
]
return UIMenu(title: "Select source", children: menuItems)
}
//codes omitted...
//MARK: pick Photo using Gallery...
func pickPhotoFromGallery(){
var configuration = PHPickerConfiguration()
configuration.filter = PHPickerFilter.any(of: [.images])
configuration.selectionLimit = 1
let photoPicker = PHPickerViewController(configuration: configuration)
photoPicker.delegate = self
present(photoPicker, animated: true, completion: nil)
}
//codes omitted...
}
//MARK: adopting required protocols for PHPicker...
extension AddExpenseViewController:PHPickerViewControllerDelegate{
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
dismiss(animated: true)
print(results)
let itemprovider = results.map(\.itemProvider)
for item in itemprovider{
if item.canLoadObject(ofClass: UIImage.self){
item.loadObject(ofClass: UIImage.self, completionHandler: { (image, error) in
DispatchQueue.main.async{
if let uwImage = image as? UIImage{
self.addExpenseScreen.buttonTakePhoto.setImage(
uwImage.withRenderingMode(.alwaysOriginal),
for: .normal
)
self.pickedImage = uwImage
}
}
})
}
}
}
}
Previous6.4. AddExpenseViewController: UIMenu for buttonTakePhotoNext6.6. Using Camera: UIImagePickerController
Last updated