【问题标题】:dismiss share extension custom viewcontroller关闭共享扩展自定义视图控制器
【发布时间】:2017-09-26 00:36:32
【问题描述】:

我正在尝试创建一个自定义视图控制器以与共享扩展一起使用。一切正常,但我不知道如何关闭自定义视图控制器。基本上我从 safari 启动我的共享扩展,并希望完全消除它并返回到 safari 视图。我知道这应该不难,但我是分享扩展的新手。下面是我的基本代码。谢谢。鲍勃

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

【问题讨论】:

  • bug 修复了吗

标签: ios swift share viewcontroller


【解决方案1】:

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

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())

【讨论】:

  • 对于 Xcode 8.3,我必须修改为: self.extensionContext!.completeRequest(returningItems: nil, completionHandler: nil) - 但那行得通!谢谢。感谢您的帮助。
  • 对不起,忘了更新swift 3的代码,你说得对
  • @OliverM 添加此行后仍然无法正常工作
  • NSError() 在运行时 (swift5) 崩溃。你应该返回NSError(domain: "com.domain.name", code: 0, userInfo: nil)
  • 不要将空的 NSError() 实例传递给 cancelRequest 方法,否则会导致 EXC_BAD_INSTRUCTION 崩溃。您可以使用主包的标识符作为域:NSError(domain: Bundle.main.bundleIdentifier!, code: 0)
【解决方案2】:

对于那些试图从 viewDidLoad 中执行此操作的人,您需要设置一个小计时器,否则它将不起作用:

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

【讨论】:

    猜你喜欢
    • 2018-03-23
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多