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.

Figure 1: PHPicker

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. 

Figure 2: PHPicker out of process working flow

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

Figure 3: PHPicker API components

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

Recent Posts
Showing 76 comments
  • yadongbiz
    Reply

    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! 야한동영상

  • yahanvideonet
    Reply

    Hello, I enjoy reading through your article post. I like to write a little comment to support you. 일본야동

  • koreayadongcom
    Reply

    Excellent post! We will be linking to this great content on our skull rings web site. Keep up the good writing. 한국야동닷컴

  • japanyadongcom
    Reply

    There is certainly a lot to learn about this topic. I really like all the points you made. 국산야동

  • chinayadongnet
    Reply

    Good way of explaining, and pleasant post to obtain information about my presentation focus, which i am going to present in college 중국야동넷

  • programming help
    Reply

    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/

  • Katie Thompson
    Reply

    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!

  • homework help australia
    Reply

    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/

  • Seth Morris
    Reply

    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

  • Assignment Help
    Reply

    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.

  • Jen Davis
    Reply

    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

  • cupcake 2048
    Reply

    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

  • GOSTOPSITE33
    Reply

    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.
    고스톱

  • TOTOSITEWEB33
    Reply

    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.
    토토사이트

  • GUIDE1903
    Reply

    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.
    일본야동

  • TOTOSAFEDB33
    Reply

    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…
    토토사이트

  • Reply

    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.

  • Reply

    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.

  • Karur vysya
    Reply

    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.

  • 먹튀검증사이트
    Reply

    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. 먹튀검증사이트

    • zxZxazx
      Reply

      Great post! We are linking to this particularly great content on our site.
      Keep up the good writing.

      온라인바카라

  • 사설토토사이트
    Reply

    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! 사설토토사이트

  • 먹튀검증사이트
    Reply

    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 😀 먹튀검증사이트

  • Marta
    Reply

    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.

  • run 3
    Reply

    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

  • 안전토토사이트
    Reply

    I had a lot of fun at this Olympics, but something was missing. I hope there’s an audience next time.안전토토사이트
    bb

  • fireboy and watergirl
    Reply

    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

  • casinosite777.info
    Reply

    Well I truly enjoyed reading it. This subject offered by you is very helpful and accurate.
    카지노사이트

  • baccaratsite.top
    Reply

    Thanks for sharing this marvelous post.
    바카라사이트

  • safecasinosite.net
    Reply

    Thank you for sharing this information.
    바카라사이트

  • baccaratsite.biz
    Reply

    I have enjoyed a lot reading this post keep it up.
    온라인카지노

  • betmate
    Reply

    이용이유가생기는곳 먹튀검증 안전노리터 go

  • totoguy
    Reply

    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메이저토토

  • totovi
    Reply

    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. 토토사이트추천

  • totoright
    Reply

    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. 메이저놀이터

  • 토디즈
    Reply

    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. 토디즈

  • Reply

    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. 토토사이트커뮤니티

  • 가입머니
    Reply

    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. 가입머니

  • 안전놀이터
    Reply

    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! 안전놀이터

  • 안전토토사이트
    Reply

    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. 안전토토사이트

  • 꽁머니지급
    Reply

    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. 꽁머니지급

  • 먹튀폴리스
    Reply

    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. 먹튀폴리스

  • ELLA JACK
    Reply

    Assignment Help USA provides 100% original solutions to the students so that teachers and professors will award them high marks. For more information, visit our website now.

  • 안전한놀이터
    Reply

    That’s a really impressive new idea! 안전한놀이터 It touched me a lot. I would love to hear your opinion on my site. Please come to the site I run once and leave a comment. Thank you.

  • khushijoshi
    Reply

    thank you for your sharing, it is very helpful to me and many others. I will visit often to read your new posts. Please continue to uphold!

  • Reply

    It’s amazing. I want to learn your writing skills. In fact, I also have a website. If you are okay, please visit once and leave your opinion. Thank you. 바카라게임사이트
    fhdh

  • 메이저토토추천
    Reply

    I’m impressed, I have to admit. Truly rarely should i encounter a blog that’s both educative and entertaining, and without a doubt, you’ve hit the nail within the head. Your notion is outstanding; the pain is an issue that insufficient everyone is speaking intelligently about. I am very happy that we stumbled across this inside my try to find some thing relating to this. 메이저토토추천

  • 먹튀검증
    Reply

    Thank you for some other informative blog. Where else could I get that type of information written in such an ideal means? I have a mission that I’m just now working on, and I have been at the look out for such information. 먹튀검증 It helped me a lot. If you have time, I hope you come to my site and share your opinions. Have a nice day.

  • harry
    Reply

    I found that site very usefull and this survey is very cirious, I ‘ ve never seen a blog that demand a survey for this actions, very curious… 안전놀이터

  • harry
    Reply

    I felt very happy while reading this site. This was really very informative site for me. I really liked it. This was really a cordial post. Thanks a lot!. 토토사이트

  • harry
    Reply

    I was reading your article and wondered if you had considered creating an ebook on this subject. Your writing would sell it fast. You have a lot of writing talent. comprar carta de condução verdadeira

  • harry
    Reply

    Nice knowledge gaining article. This post is really the best on this valuable topic. Chicks truck

  • hamza soomro
    Reply

    This content is simply exciting and creative. I have been deciding on a institutional move and this has helped me with one aspect. led light strip solar

  • Reply

    I love your creativity. Are you also searching for nursing admission essay help? we are the best solution for you. We are best known for delivering quality essay writing services to students without having to break the bank

  • Reply

    Your blogs are great. Are you also searching for nursing capstone writing project? we are the best solution for you. We are best known for delivering quality nursing capstone writing services to students without having to break the bank

  • Reply

    I love this. It is soo informative. Are you also searching for cheap assignment writing services we are the best solution for you. We are best known for delivering the best services to students without having to break the bank

  • 토토사이트
    Reply

    Excellent blog here! Also your site loads up very fast! What host are you using? Can I get your affiliate link to your host?토토사이트

  • 안전토토사이트
    Reply

    After study several of the blogs with your website now, i truly much like your strategy for blogging. I bookmarked it to my bookmark web site list and will be checking back soon. Pls look at my internet site at the same time and make me aware if you agree.안전토토사이트

  • 메이저토토사이트
    Reply

    I want to to thank you for this good read!! I definitely enjoyed every little bit of it. I’ve got you book-marked to look at new stuff you post… 메이저토토사이트

  • 토토사이트
    Reply

    “This post will assisst the internet viewers for creating new web
    site or even a weblog from start to end.” 토토사이트

  • casinosite
    Reply

    I came to this site with the introduction of a friend around me and I was very impressed when I found your writing. I’ll come back often after bookmarking! casinosite

  • ern
    Reply

    Can I just say what a comfort to uncover a person that genuinely knows what they are discussing online.
    You actually realize how to bring an issue to light and make it important.
    More people should look at this and understand this side of the story.
    I was surprised you aren’t more popular
    since you definitely have the gift.

    슬롯사이트

  • casinocommunity
    Reply

    As I am looking at your writing, casinocommunity I regret being unable to do outdoor activities due to Corona 19, and I miss my old daily life. If you also miss the daily life of those days, would you please visit my site once? My site is a site where I post about photos and daily life when I was free.

  • bitcoincasino
    Reply

    It’s too bad to check your article late. I wonder what it would be if we met a little faster. I want to exchange a little more, but please visit my site bitcoincasino and leave a message!!

  • Alaan
    Reply

    Thank you very much because this blog is very useful and the content is very cool
    https://theisland360.com/blog-112/essence-of-argan-australia-reviews/

  • casinocommunity
    Reply

    I am very impressed with your writing casinocommunity I couldn’t think of this, but it’s amazing! I wrote several posts similar to this one, but please come and see!

  • zxZxazx
    Reply

    Great post! We are linking to this particularly great content on our site.
    Keep up the good writing.

    온라인바카라

  • 토토사이트
    Reply

    이 기사에는 내가 스스로 생각하지 못했을 것이 너무 많습니다. 귀하의 콘텐츠는 독자에게 흥미로운 방식으로 생각할 수있는 것들을 제공합니다. 토토사이트

  • 그래프게임
    Reply

    Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me. 그래프게임

  • 해시게임
    Reply

    Your blog is too much amazing. I have found with ease what I was looking. Moreover, the content quality is awesome. Thanks for the nudge! 해시게임

  • 코인카지노
    Reply

    New web site is looking good. Thanks for the great effort. 코인카지노

  • 먹튀검증
    Reply

    This is a great article, Given such a great amount of information in it, These kind of articles keeps the clients enthusiasm for the site, and continue sharing more … 먹튀검증

  • 슬롯
    Reply

    Very likely I’m going to bookmark your blog . You absolutely have wonderful stories. Cheers for sharing with us your blog 슬롯

  • 카지노사이트
    Reply

    Nice knowledge gaining article. This post is really the best on this valuable topic. 카지노사이트

Leave a Comment

Contact Us

We look forward to your messages. Please drop us a note for any enquiries and we'll get back to you, asap.

Not readable? Change text. captcha txt
Prelaunch1