Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get items from extension context in Share extension for iOS?

Once my share extension is loaded, not everytime and not everything is visible for user immediately. The most common is that there you can see image, number of images, and content text. However there are cases where there is a lot more informations.

  • How to get access to them?

I know that within SLComposeServiceViewController there is extensionContext and its inputItems property.

Ok, so I stopped the debugger at time, and print out on console some things with following command:

po (extensionContext!.inputItems[0] as! NSExtensionItem).userInfo![NSExtensionItemAttachmentsKey]
  • Is it correct way to do this?
  • Is there usually one input item?

there was two NSItemProvider objects as attachments to first NSExtensionItem

enter image description here

Ok, then I print out the first of attachments:

enter image description here

  • How to get that image from that NSItemProvider and url from the next one? Can you deliver some code?

I suppose we will use

loadItemForTypeIdentifier(_:options:completionHandler:)

but do not know how.

like image 378
Bartłomiej Semańczyk Avatar asked Oct 27 '25 15:10

Bartłomiej Semańczyk


1 Answers

  1. import MobileCoreServices

  2. There is a simple function you can apply to your code:

    private func fetchAndSetContentFromContext() {
    
        guard let extensionItems = extensionContext?.inputItems as? [NSExtensionItem] else {
            return
        }
    
        for extensionItem in extensionItems {
            if let itemProviders = extensionItem.attachments as? [NSItemProvider] {
                for itemProvider in itemProviders {
                    if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeText as String) {
    
                        itemProvider.loadItemForTypeIdentifier(kUTTypeText as String, options: nil, completionHandler: { text, error in
    
                        })
                    }
                }
            }
        }
    }
    
like image 77
Bartłomiej Semańczyk Avatar answered Oct 30 '25 07:10

Bartłomiej Semańczyk