42

I have a UIDocumentPickerViewController that picks only images. This works fine in iOS 13:

let supportedTypes: [String] = ["public.image"]
let documentPickerViewController = UIDocumentPickerViewController(documentTypes: supportedTypes, in: .import)

I'm trying to achieve the same in iOS 14.

However, init(documentTypes:in:) was deprecated in iOS 14.0.

So I'm assuming I have to use this initializer instead: init(forOpeningContentTypes:asCopy:)

The forOpeningContentTypes argument expects an array of UTType.
I'm not sure how to use / import it.
Is it like [UTType.Image]?

let supportedTypes: [UTType] = [UTType.Image]
self.viewController = UIDocumentPickerViewController(forOpeningContentTypes: supportedTypes, asCopy: true)

This won't even compile because Cannot find type 'UTType' in scope.
I also tried import MobileCoreServices and even import CoreServices, but that didn't help.

The documentation for the new Document Picker initializer points to this UTTypeReference -- so I tried using that, but it can't be found either.

How can I have a UIDocumentPickerViewController that picks only images in iOS 14?

Update

This works (thanks @Warren):

import UniformTypeIdentifiers
let supportedTypes: [UTType] = [UTType.image]
let pickerViewController = UIDocumentPickerViewController(forOpeningContentTypes: supportedTypes, asCopy: true)
backslash-f
  • 7,923
  • 7
  • 52
  • 80

1 Answers1

56

Add import UniformTypeIdentifiers to your swift file to get access to UTType

See the documentation for more usages.

And the WWDC2020 video "Build document-based apps in SwiftUI" for a practical demo.

Warren Burton
  • 17,451
  • 3
  • 53
  • 73
  • 9
    It's ridiculous that Apple doesn't import `UniformTypeIdentifiers` in `UIDocumentPickerViewController`'s declaration. – Léo Natan Oct 27 '21 at 13:58
  • 1
    How would one know this from looking here https://developer.apple.com/documentation/uniformtypeidentifiers/uttypereference just curious, thanks. – Dan Rosenstark Apr 04 '23 at 15:08
  • Inference and the UT namespace. The documentation references UTType as a core type and when you look up UTType you can see it’s a member of that module. Not easy for a person to get a direct answer however. – Warren Burton Apr 04 '23 at 22:30