我正在尝试创建要与共享扩展一起使用的自定义 View Controller 。一切正常,但我不知道如何关闭自定义 View Controller 。基本上,我从safari启动我的共享扩展程序,并希望完全忽略它并返回到safari View 。我知道这应该不难,但是我是新来的共享扩展。下面是我的基本代码。谢谢。鲍勃

//
//  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")
        }
    }
}

最佳答案

您应该使用以下两个调用之一结束共享扩展:

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

self.extensionContext!.cancelRequestWithError(NSError())

Apples share extension docs

swift 更新4:
self.extensionContext!.completeRequest(returningItems: nil, completionHandler: nil)

self.extensionContext!.cancelRequest(withError:NSError())

09-16 02:05