SWIFT: PHPicker – Best way to access photo and video data from Photos
Importing photos and videos as media is a common feature used by many iOS applications. There are two methods for doing that: either by utilizing a given framework or by implementing a custom picker. The second method is significantly more complicated. Here, we focus on the first option. iOS 14 introduced a brand new photo picker controller, the PHPicker API.
Up until iOS 13, the available photo picker was UIImagePickerController, a familiar view controller that made its debut many years back. UIImagePickerController has provided dual functionality; photos and videos are imported to the app. The other captures new media using a camera from the iPhone or iPad.
However, this controller has two disadvantages; the first is that it provides a relatively limited environment to pick media items. Users can select one photo or video at each time only and there is no option to search amongst photos or videos stored in the user’s library. The second downside is that developers are required to ask users for their consent, and then add new entries in the app’s Info.plist file with a description of the intended use.
PHPicker changes all that and makes importing photos and videos faster and more effortless. First of all, its most fantastic feature is that it allows single and multiple item selection, which users greatly appreciate. In addition, it offers a search feature in a picker similar to the Photos app, so users see a familiar UI; they already know what to do when such a picker is presented to them.
What is PHPicker?
PHPicker is the system-provided Picker that allows you to access photos and videos from the user’s photo library. It has built-in support for search, just like the photos app. It supports fluid zooming in the grid, and a highly requested feature, multi-select for third-party apps, where users can even review their selection.
Features
- All-new design
- A new easy to use API
- Supports multi-selection
- Can specify the selectable types
Another significant feature is that PHPicker has privacy built-in by default. It does not need direct access to the photos library to show the picker, and the picker will not prompt for access on behalf of the app. It provides the user-selected photos and videos only, which indicates the clear users’ intent of sharing the assets with your app.
PHPicker runs processes outside of the app even though it looks like PHPicker runs inside the app. The app cannot access the picker directly and cannot even take screenshots of the picker content. Only photos and videos selected by the user are passed back to the host app (Figure 2).
NEW API
PHPickerConfiguration is used to specify the multi-select limit or with an optional PHPickerFilter, to choose the selectable types. The configuration is passed to PHPickerController during its initialization. Set a delegate to implement it in your app to get a response. Once a user confirms the selection, the picker creates PHPickerResult objects then passes them back to the delegate.
Let’s have a look at how it works in code.
var configuration = PHPickerConfiguration()
// "unlimited" selection by specifying 0, default is 1
configuration.selectionLimit = 0
// Only show images (including Live Photos)
configuration.filter = .images
// Only videos or Live Photos (for their video complement), but no images
configuration.filter = .any(of: [.videos, .livePhotos])
As I already mentioned, you can use a configuration to specify the selection limit and filter the visible item types.
First, we initialize the configuration.
var configuration = PHPickerConfiguration()
You can specify a selection limit for the picker. The default limit is one, and to allow unlimited selection, set the selection limit to zero.
// "unlimited" selection by specifying 0, default is 1
configuration.selectionLimit = 0
You can then specify a filter to restrict the types of selected items. For example, use the images filter if you only want to show images, including live photos.
// Only show images (including Live Photos)
configuration.filter = .images
You can even combine photos. The picker will only show videos and live photos in this example but no images.
// Only videos or Live Photos (for their video complement), but no images
configuration.filter = .any(of: [.videos, .livePhotos])
The PHPickerViewController is initialized with the configuration. First, let’s create a configuration and then pass the configuration to the picker ViewController during initialization. Assign a delegate to the picker and present the picker.
let configuration = PHPickerConfiguration()
// Initialize picker view controller with a configuration
let picker = PHPickerViewController(configuration: configuration)
// Assign a delegate
picker.delegate = self
// The client is responsible for presentation and dismissal
present(picker, animated: true)
Please note that your app is responsible for the presentation and dismissal of the picker. The picker does not manage the display itself.
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
// The client is responsible for presentation and dismissal
picker.dismiss (animated: true)
// Get the first item provider from the results
let itemProvider = results.first?.itemProvider
// Access the UIImage representation for the result
If let itemProvider = itemProvider, itemProvider.canLoadObject(ofClass: UIImage.self) {
itemProvider.loadObject(ofClass: UIImage.self) { image, error in
if let image = image {
// Do something with the UIImage
}
}
}
Once the user confirms this selection, the delegate method will be called. So first, let’s dismiss the picker. Then you can ask the result object for an NSItemProvider. The itemProvider presents multiple different representations of the selected item. First, ask the provider if it can load the type you want to load and then actually load it. Then your app can do something with the image.
Remember that the item provider API is async, and you should handle any errors occurring here.
Short full example here:
struct ContentView: View {
@State private var isPresented: Bool = false
var body: some View {
Button("Present Picker") {
isPresented.toggle()
}.sheet(isPresented: $isPresented) {
let configuration = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
PhotoPicker(configuration: configuration, isPresented: $isPresented)
}
}
}
struct PhotoPicker: UIViewControllerRepresentable {
let configuration: PHPickerConfiguration
@Binding var isPresented: Bool
func makeUIViewController(context: Context) -> PHPickerViewController {
let controller = PHPickerViewController(configuration: configuration)
controller.delegate = context.coordinator
return controller
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) { }
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
// Use a Coordinator to act as your PHPickerViewControllerDelegate
class Coordinator: PHPickerViewControllerDelegate {
private let parent: PhotoPicker
init(_ parent: PhotoPicker) {
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
print(results)
// Set isPresented to false because picking has finished.
parent.isPresented = false /
}
}
}
For more details, check out the Apple documentation here: https://developer.apple.com/documentation/photokit/phpickerviewcontroller#topics
Wonderful web site. Plenty of helpful information here. I am sending it to a few pals and additionally sharing in delicious. And obviously, thank you to your sweat! 야한동영상
Hello, I enjoy reading through your article post. I like to write a little comment to support you. 일본야동
Excellent post! We will be linking to this great content on our skull rings web site. Keep up the good writing. 한국야동닷컴
There is certainly a lot to learn about this topic. I really like all the points you made. 국산야동
Good way of explaining, and pleasant post to obtain information about my presentation focus, which i am going to present in college 중국야동넷
Would you mind to get served by a global leader of programming help? Of course not! Take a moment and get onboard to our World class assignment help writing services ata cost-effective price.
https://www.gotoassignmenthelp.com/assignment-help/do-my-assignment-online/
Like a previous college or university college student, I know how challenging dealing with admission documents might possibly be. Whatever the essay model you’re required to submit, it may take lots of your time when you are making an attempt to get it done on your own. To minimize strain and conserve some time, I counsel you to start looking for some specialized crafting products and get a top-notch paper right away, you won’t regret it after you are attempting it!
GotoAssignmenthelp is the proficient academic writing service holding a resourceful team of more than 3,000 assignment tutors, dedicated to assist students with the authentic academic support
https://www.gotoassignmenthelp.com/essay-help/do-my-essay/
How complicated is it to look through the list of argumentative research paper topics and choose the one you like the most? Surf the website to simplify your task and get inspired by the most appealing themes.
https://superbgrade.com/blog/30-good-argumentative-research-paper-topics-and-ideas
Hey, I liked your article and it was a good and interesting read. I am bookmarking your site and will visit time to time to read more from you. Thank you.
Guys, are some coffee experts here? Can anyone tell me if I can trust these costa rican coffee reviews published online? I just want to be sure I use good beans. https://coffeelikeapro.com/coffee-beans/best-costa-rican-coffee-beans
I’ve read some good stuff here. Definitely worth bookmarking for revisiting. I surprised how much effort you put to create such a great informative website
I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.
고스톱
I can’t imagine focusing long enough to research; much less write this kind of article. You’ve outdone yourself with this material. This is great content.
토토사이트
Good to become visiting your weblog again, it has been months for me. Nicely this article that I’ve been waited for so long. I will need this post to total my assignment in the college, and it has exact same topic together with your write-up. Thanks, good share.
일본야동
Hello really awesome web site!! Guy .. Beautiful .. Wonderful .. I’ll bookmark your site and consider the feeds moreover. I am pleased to search out beneficial details appropriate here inside of the published material, thanks for sharing…
토토사이트
Seek help from your assignment writing service, you can avail optimum support on different types of report writing. You may need help with business assignment writing or technical report writing regardless of the type, and our writers will come up with accurate solutions every time.
I am happy to be here and this wonderful blog. I have found here lots of important information for my knowledge I need. Thanks for sharing this amazing post.
Hello, I enjoyed your article and found it to be a good and interesting read. I’ve bookmarked your site and will return from time to time to read more from you. Thank you very much.
Excellent information on your blog, thank you for taking the time to share with us. Amazing insight you have on this, it’s nice to find a website that details so much information about different artists. 먹튀검증사이트
Excellent blog you have here.. It’s hard to find good quality writing like yours these days. I truly appreciate individuals like you! Take care! 사설토토사이트
Interesting! I was thinking the same thing as you. Your article explains my vague thoughts very clearly. Thank you. I have a lot of interesting ideas. I want you to look at the post I wrote 😀 먹튀검증사이트
I am a journalist and writer. When I was a student it was a hard time and I had to resolve a number of problems with my admission process. It was so stressful to complete all the motivation letters and private statements. I tried so challenging and ultimately entered the university of my dream. It was But know it is easy to save quite a lot of your time and get a private statement of your dream with significantly less effort. I can advise resources that can assure exceptional and high-quality solutions.
A really excellent site; I enjoy the way you provide information in an open and entertaining manner; I learned a lot from my blog. moto x3m
I had a lot of fun at this Olympics, but something was missing. I hope there’s an audience next time.안전토토사이트
bb
Thank you so much for sharing such great information with us. Your website is great. We are very impressed by the details that you have on your website. We have bookmarked this site. keep it up and thanks again.
poppy playtime
Well I truly enjoyed reading it. This subject offered by you is very helpful and accurate.
카지노사이트
Thanks for sharing this marvelous post.
바카라사이트
Thank you for sharing this information.
바카라사이트
I have enjoyed a lot reading this post keep it up.
온라인카지노
슬롯커뮤니티
Royalcasino110
이용이유가생기는곳 먹튀검증 안전노리터 go
Hello, I’m happy to see some great articles on your site. Would you like to come to my site later? My site also has posts, comments and communities similar to yours. Please visit and take a look메이저토토
I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post. Come and check it out. 토토사이트추천
There are some great posts on your site. COVID-19 is serious all over the world, so be careful about your health. And please subscribe more often. 메이저놀이터
For a long time me & my friend were searching for informative blogs, but now I am on the right place guys, you have made a room in my heart! It is extraordinary to have the chance to peruse a decent quality article with valuable data on subjects that bounty are intrigued one.I agree with your decisions and will enthusiastically anticipate your future updates. It is a completely interesting blog publish.I often visit your posts for my project’s help about Diwali Bumper Lottery and your super writing capabilities genuinely go away me taken aback.Thank you a lot for this publish. 토디즈
Your article got me thinking about something. Who do we contact if we want anesthesia quickly? I have heard there are some mobile services online, and now I know which of these services is best at their job. I am glad my friends told me about them. Wow! Such an amazing and helpful post this is. I really really love it. It’s so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also. Awesome dispatch! I am indeed getting apt to over this info, is truly neighborly my buddy. Likewise fantastic blog here among many of the costly info you acquire. Reserve up the beneficial process you are doing here. 토토사이트커뮤니티
I am impressed. I don’t think Ive met anyone who knows as much about this subject as you do. You are truly well informed and very intelligent. You wrote something that people could understand and made the subject intriguing for everyone. Really, great blog you have got here. I am always searching online for storys that can accommodate me. There is obviously a multiple to understand about this. I feel you made few salubrious points in Attributes moreover. Detain busy, awesome career! You bear through a awesome vacancy. I sanity definitely quarry it moreover personally suggest to my buddys. I am self-possessed they determination be benefited from this scene. 가입머니
Thanks for the wonderful share. Your article has proved your hard work and experience you have got in this field. Brilliant .i love it reading. I’m sure I will at last make a move using your tips on those things I could never have been able to touch alone. You had been so innovative to let me be one of those to benefit from your useful information. Please know how much I am thankful. Really decent post. I just discovered your blog and wished to say that I have truly cherished surfing around your blog entries. Regardless I’ll be subscribing for your nourish and I trust you compose afresh soon! 안전놀이터
Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have. I really loved reading your blog. It was very well authored and easy to understand. Unlike other blogs I have read which are really not that good.Thanks alot! Your work is very good and I appreciate you and hopping for some more informative posts . Really impressive post. I read it whole and going to share it with my social circules. I enjoyed your article and planning to rewrite it on my own blog. 안전토토사이트
I was just browsing through the internet looking for some information and came across your blog. I am impressed by the information that you have on this blog. It shows how well you understand this subject. Bookmarked this page, will come back for more. Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free . Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. 꽁머니지급
I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. Fabulous post. Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites. I’ll be sure to check back again real soon. I like this post,And I guess that they having fun to read this post,they shall take a good site to make a information,thanks for sharing it to me. 먹튀폴리스