The Photo Picker and PHPickerViewController allow developers to easily integrate photo selection functionality into their iOS applications. This is beneficial for apps that require the user to select images or videos, as it provides a user-friendly interface while maintaining privacy by not giving direct access to the user's photo library.
To implement the PHPickerViewController in your Swift application, follow these steps:
import UIKit
import PhotosUI
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func selectPhoto(_ sender: UIButton) {
var config = PHPickerConfiguration()
config.selectionLimit = 1 // allows selecting only one photo
config.filter = .images // allows only images to be selected
let picker = PHPickerViewController(configuration: config)
picker.delegate = self
present(picker, animated: true, completion: nil)
}
}
extension ViewController: PHPickerViewControllerDelegate {
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true, completion: nil)
guard let result = results.first else { return }
result.itemProvider.loadObject(ofClass: UIImage.self) { (object, error) in
if let image = object as? UIImage {
// Use the selected image
}
}
}
}
This code sets up a simple interface where pressing a button presents the photo picker. The selected image is then loaded using the `loadObject` method.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?