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

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

问题描述:

我有一个Mac应用程序,它读取格式化文本,图像存储为NSAttributedString。我想将其转换为包含图像的HTML。如何从NSAttributedString获取NSTextAttachment的图像名称

获取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" 

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

+0

'fileWrapper.preferredFilename'? – Willeke

以供参考:使用fileWrapper.preferredFilename而不是​​(谢谢@Willeke)。谁会想到有两个属性...