Initialization of UIDocumentPickerViewController in iOS 14
Asked Answered
D

1

43

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)
Desegregate answered 30/6, 2020 at 8:12 Comment(2)
You need UniformTypeIdentifiers framework for UTType – Hanafee
@WarrenBurton if you write an answer, I could accept it. – Desegregate
H
62

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.

Hanafee answered 30/6, 2020 at 15:35 Comment(3)
It's ridiculous that Apple doesn't import UniformTypeIdentifiers in UIDocumentPickerViewController's declaration. – Automatic
How would one know this from looking here developer.apple.com/documentation/uniformtypeidentifiers/… just curious, thanks. – Kellogg
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. – Hanafee

© 2022 - 2024 β€” McMap. All rights reserved.