2016-12-01 178 views
1

我有一個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

回答

1

以供參考:使用fileWrapper.preferredFilename而不是​​(謝謝@Willeke)。誰會想到有兩個屬性...