【问题标题】:How to associate existing file type for Mac OS application in XCode 7?如何在 XCode 7 中关联 Mac OS 应用程序的现有文件类型?
【发布时间】:2016-06-11 07:04:30
【问题描述】:

我正在 Xcode 7 中为 jpeg 图片制作一个简单的查看器,并尝试将 Jpeg 文件类型与我的应用程序相关联。这是一个用于 Swift 中 OS X 的 Cocoa 应用程序,它使用情节提要,而不是基于文档的应用程序。

我在网上找到的教程建议通过信息选项卡,在那里添加一个新的文档类型。现在这就是事情开始与教程中的不同的地方:其中只有 3 个字段需要填写(名称、类型、图标),但我还有更多。我试着四处试验,这是我在我得到的字段中输入的内容:

  • 名称:JPEG 图片
  • 类:留空
  • 扩展名:.jpg、.jpeg、.JPEG、.JPG
  • 图标:留空
  • 标识符:public.jpeg
  • 角色:查看者
  • Mime 类型:图像/jpeg
  • “文档作为捆绑分发”默认部分选中;我只是保持原样。
  • 也没有触及其他文档类型属性。

结果,当我二次单击 Jpeg 文件以及其他已安装的应用程序时,我的应用程序显示在“打开方式”的列表中,但是一旦我尝试以这种方式打开它,我会弹出一个提示 无法打开文件“picture.jpg”。 MyApp 无法打开“JPEG 图像”格式的文件

我做错了什么?

【问题讨论】:

  • 向我们展示您的代码。你尝试了什么?
  • 除了上述之外真的没有别的了。该代码没有任何特定于处理打开的文件的内容。我只是还没到那里。我想我做错了什么?

标签: xcode macos cocoa file-association


【解决方案1】:

Class字段是必须的,你必须有相应的实现。

试试:

Class: $(PRODUCT_MODULE_NAME).Document

然后添加Document.swift:

import Cocoa

class Document : NSDocument
{

    override init() {
        super.init()
        // Add your subclass-specific initialization here.
    }

    override class func autosavesInPlace() -> Bool {
        return true
    }

    override func makeWindowControllers() {
        // Returns the Storyboard that contains your Document window.
        let storyboard = NSStoryboard(name: "Main", bundle: nil)
        let windowController = storyboard.instantiateController(withIdentifier: "Document Window Controller") as! NSWindowController
        self.addWindowController(windowController)
    }

    override func data(ofType typeName: String) throws -> Data {
        // Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil.
        // You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
        throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
    }

    override func read(from data: Data, ofType typeName: String) throws {
        // Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false.
        // You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead.
        // If you override either of these, you should also override -isEntireFileLoaded to return false if the contents are lazily loaded.
        throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
    }

}

^ 根据需要修改。

另外,你指定了角色“查看者”,意味着你可以用空格键打开它,而不是双击(打开)——这就是角色“编辑”对吧?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 2011-02-15
    相关资源
    最近更新 更多