Juliette Destang
Juliette Destang

Reputation: 45

How to use UTType with a UIDocumentPicker (pages? docx?)

I'm trying to open a picker with only certain file types allowed. I'm using this documentation to find the UTType I need: https://developer.apple.com/documentation/uniformtypeidentifiers/uttype/system_declared_uniform_type_identifiers

But I can't find a UTType for .pages, .doc, .docx for example.

What should I do?

This is my code for the moment

func presentPickerDocument() {
    //Create a picker specifying file type and mode
    var supportedTypes: [UTType]
    supportedTypes = [UTType.pdf, UTType.url]

    let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: supportedTypes, asCopy: true)
    documentPicker.delegate = self
    documentPicker.allowsMultipleSelection = false
    present(documentPicker, animated: true, completion: nil)
}

Upvotes: 3

Views: 4189

Answers (3)

j.s.com
j.s.com

Reputation: 1478

There is a little error in the for-loop. It must be:

for i in 0..<stringArray.count

Because 0 is the first element and count - 1 the last one. The complete function must be look like:

func stringarray2content (_ stringArray: [String]) -> [UTType]
{
    var contentArray: [UTType] = []
    if (stringArray.count > 0)
    {
        for i in 0..<stringArray.count
        { 
            contentArray.append(UTType(tag: stringArray[i], tagClass: .filenameExtension, conformingTo: nil)!)
        }
    }
    return (contentArray)
}

Upvotes: -1

user23553714
user23553714

Reputation:

I have written a small func to convert a string array to a UTType array to use with filetypes. This works only with macOS 11 and later projects.

func stringarray2content (_ stringArray: [String]) -> [UTType]
{
    var contentArray: [UTType] = []
    if (stringArray.count > 0)
    {
        for i in 1...stringArray.count
        {
            contentArray.append(UTType(tag: stringArray[i], tagClass: .filenameExtension, conformingTo: nil)!)
        }
    }
    return (contentArray)
}

Please make sure you have included the library for UTType:

import UniformTypeIdentifiers

Upvotes: 1

Sweeper
Sweeper

Reputation: 274805

You can create a UTType from a file extension like this:

UTType(tag: "pages", tagClass: .filenameExtension, conformingTo: nil)

This creates a UTType?, as there can be no UTType associated with the given file extension.

You can also use:

UTType(filenameExtension: "pages")

but this only finds a UTType if the file extension inherits from public.data, so it won't work for all the file extensions.

On macOS Terminal, you can also use the mdls command to inspect the Uniform Type Identifier of a file

mdls -name kMDItemContentType yourFile.pages

Or its entire tree:

mdls -name kMDItemContentTypeTree yourFile.pages

After that you can create a UTType using its identifier like this:

UTType("com.apple.iwork.pages.sffpages")

Upvotes: 10

Related Questions