Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dismiss share extension custom viewcontroller

I am trying to create a custom view controller to be used with a share extension. Everything works, but I don't know how to dismiss the custom view controller. Basically I launch my share extension from safari and want to completely dismiss this and return back to the safari view. I know this should not be hard, but I am new to share extensions. Below is my base code. Thanks. Bob

//
//  ShareViewController.swift
//  ShareExtension


import UIKit
import Social
import MobileCoreServices

class ShareViewController: UIViewController {
    private var url: NSURL?


    @IBAction func backButton(_ sender: Any) {
        print("back button pressed")

       self.dismiss(animated: true, completion: nil)
    }


    override func viewDidLoad()  {
        super.viewDidLoad()
    }


    private func getURL() {
        let extensionItem = extensionContext?.inputItems.first as! NSExtensionItem
        let itemProvider = extensionItem.attachments?.first as! NSItemProvider
        let propertyList = String(kUTTypePropertyList)
        if itemProvider.hasItemConformingToTypeIdentifier(propertyList) {
            itemProvider.loadItem(forTypeIdentifier: propertyList, options: nil, completionHandler: { (item, error) -> Void in
                guard let dictionary = item as? NSDictionary else { return }
                OperationQueue.main.addOperation {
                    if let results = dictionary[NSExtensionJavaScriptPreprocessingResultsKey] as? NSDictionary,
                        let urlString = results["URL"] as? String,
                        let url = NSURL(string: urlString) {
                        self.url = url
                    }
                }
            })
        } else {
            print("error")
        }
    }
}
like image 914
Robert Marlan Avatar asked Apr 28 '17 02:04

Robert Marlan


2 Answers

You should end your sharing extensions work with one of these two calls:

self.extensionContext!.completeRequestReturningItems(nil, completionHandler: nil)

self.extensionContext!.cancelRequestWithError(NSError())

Apples share extension docs

updated for swift 4:

self.extensionContext!.completeRequest(returningItems: nil, completionHandler: nil)

self.extensionContext!.cancelRequest(withError:NSError())
like image 181
OliverD Avatar answered Nov 11 '22 20:11

OliverD


For those who are trying to do this from viewDidLoad, you need to set a small timer, otherwise it won't work:

override func viewDidLoad() {
    super.viewDidLoad()
    Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(self.didSelectPost), userInfo: nil, repeats: false)
  }
like image 30
Elendurwen Avatar answered Nov 11 '22 20:11

Elendurwen