解雇共享扩展自定义视图控制器

14

我正在尝试创建一个自定义视图控制器,用于共享扩展。 一切都正常,但我不知道如何解除自定义视图控制器。基本上,我从Safari启动我的共享扩展,并希望完全关闭它并返回Safari视图。我知道这不应该很难,但我是共享扩展的新手。以下是我的基础代码。谢谢。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")
        }
    }
}

问题已经修复了吗? - Satheeshkumar Naidu
2个回答

41

在结束共享扩展的工作时,您应使用以下两个调用之一:

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

self.extensionContext!.cancelRequestWithError(NSError())

苹果分享扩展文档

已更新至Swift 4:

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

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

2
对于Xcode 8.3,我不得不进行修改:self.extensionContext!.completeRequest(returningItems: nil, completionHandler: nil) - 但这很有效!谢谢。我感激您的帮助。 - Robert Marlan
抱歉,忘记更新 Swift 3 的代码了,你是对的。 - OliverD
1
@OliverM 在添加了这些行之后仍然不起作用。 - Satheeshkumar Naidu
关键是在关闭自定义视图控制器之前调用completeRequestReturningItems函数。 - massimobio
8
NSError()在运行时会崩溃(Swift5)。您应该返回NSError(domain: "com.domain.name", code: 0, userInfo: nil) - Lirik
4
不要向cancelRequest方法传递一个空的NSError()实例,否则会导致EXC_BAD_INSTRUCTION崩溃。您可以使用主要Bundle的标识符作为域:NSError(domain: Bundle.main.bundleIdentifier!, code: 0) - Igor Kharakhordin

4

对于那些试图在viewDidLoad中实现此操作的人,你需要设置一个小的计时器,否则它不会起作用:

override func viewDidLoad() {
    super.viewDidLoad()
    Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(self.didSelectPost), userInfo: nil, repeats: false)
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接