我有一个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
个实例,但无法确定实际的文件名(&#34; Untitled 2.jpg&#34;)。 NSFileWrapper.filename
返回nil
,但我没有看到用于从文字附件中获取名称的API。
令人沮丧的是,信息在文本附件中。如果我打印其调试说明,我会看到文件名:
<NSTextAttachment: 0x7fe68d5304c0> "Untitled 2.jpg"
<NSTextAttachment: 0x7fe68d533d60> "Pasted Graphic.tiff"
如何访问文件名? (不解析调试描述;)
答案 0 :(得分:0)
NSTextAttachment没有图片名称和图片网址的属性,这绝对是荒谬的。
我将NSTextAttachment子类化,并在初始化自定义类时添加了这些属性。
例如:
子类:
import Foundation
class CustomTextAttachment: NSTextAttachment {
var imageURL: String?
var imageTitle: String?
}
实现:
let textAttachment = CustomTextAttachment()
textAttachment.imageTitle = title
textAttachment.imageURL = url
现在,当我点按图片时:
func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool {
print("Tapped custom text attachment")
if let commentTextAttachment = textAttachment as? CustomTextAttachment, let title = commentTextAttachment.imageTitle, let link = commentTextAttachment.imageURL {
print("Got title \(title) and link \(link) for attachment")
}
return true
}