cocoa - 如何从 NSAttributedString 获取 NSTextAttachment 的图像名称

标签 cocoa nsattributedstring nstextattachment

我有一个 Mac 应用程序,可以读取存储为 NSAttributedString 的图像的格式化文本。我想将其转换为 HTML,包括图像。

获取 HTML 工作正常,我什至可以枚举附加图像,但我无法获取附加图像的实际文件名。我需要这些来生成 HTML。

获取 HTML:

let htmlData = try attrString.dataFromRange(NSMakeRange(0, attrString.length), 
documentAttributes: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType])

产生:

<p class="p1"><img src="file:///Untitled%202.jpg" alt="Untitled 2.jpg"></p>

枚举附加图像:

    attrString.enumerateAttribute(NSAttachmentAttributeName,
        inRange: NSMakeRange(0, attrString.length),
        options: [],
        usingBlock: {attachment, range, _ in

        if let attachment = attachment as? NSTextAttachment,
            let fileWrapper = attachment.fileWrapper,
            let data = fileWrapper.regularFileContents
        {
            // This prints <NSTextAttachment: 0x7fe68d5304c0> "Untitled 2.jpg"
            // But there's no API to get the name?
            print(attachment.description)
        }
    })

所以我最终得到了 NSTextAttachment 实例,但无法确定实际的文件名(“Untitled 2.jpg”)。 NSFileWrapper.filename 返回 nil 并且我没有看到用于从文本附件获取名称的 API。

令人沮丧的是,这些信息位于文本附件中。如果我打印其调试描述,我会看到文件名:

<NSTextAttachment: 0x7fe68d5304c0> "Untitled 2.jpg"
<NSTextAttachment: 0x7fe68d533d60> "Pasted Graphic.tiff"

如何访问文件名? (不解析调试描述;)

最佳答案

供将来引用:使用 fileWrapper.preferredFilename 而不是 fileWrapper.fileName (感谢@Willeke)。谁会想到有两个属性...

关于cocoa - 如何从 NSAttributedString 获取 NSTextAttachment 的图像名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40904648/

相关文章:

iOS - TextView 的图像附件更改属性

macos - 如何以编程方式确定用户是否已将其 Mac 设置为 "set date and time automatically"?

swift - NSView mouseDown 填充矩形

iphone - 为什么在 switch...case 中不省略 "case"在 XCode 中抛出错误或警告?

ios - 使用NSAttributedString不正确滚动UITextView

swift - 如何使用 swift 在 iOS 8 中插入图像 Inline UILabel

objective-c - 字符串中的字符替换

ios - 对于 iOS 8 和 iOS 9 中的某些特定范围,NSMutableAttributedString 不显示不同颜色的字符串

ios - 如何在 UILabel 上为下划线创建属性?

ios - 如何在 NSTextAttachment 中设置模板图像的颜色