swift uitextview html image causes crash when copy image is selected after long press

两盒软妹~` 提交于 2021-02-11 12:32:22

问题


I currently have a UITextView that is displaying an NSAttributedString that contains HTML data with text and images. This data is received via API so images and text are all combined into one HTML string. This is the function that parses the HTML.

let htmlData = NSString(string: myString).data(using: String.Encoding.unicode.rawValue);
let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
    NSAttributedString.DocumentType.html];
do{
    let text = try NSMutableAttributedString(data: htmlData ?? Data(), options: options, documentAttributes: nil);
    text.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "Arial", size: CGFloat(fontSize)) as Any, range: NSMakeRange(0, text.length));
    return text;
}
catch let error{
    print(error);
    return NSMutableAttributedString(string: myString);
}

When long pressing on the image, a menu appears with two options (1. Copy image 2. Save to Camera Roll). When I click on Copy image, the app crashes with this error message:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_UIConcretePasteboard setImage:]: Argument is not an object of type UIImage [(null)]'

Does anyone know how to fix this so when long pressing on the image and selecting Copy image, it will not crash?


回答1:


You need to convert images from html to NSTextAttachment, like you do it for text to NSAttributedString. And when attach these attachments to NSAttributedString.

It can look somehow like this:

let htmlData = NSString(string: myString).data(using: String.Encoding.unicode.rawValue)
let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
    NSAttributedString.DocumentType.html]
let image = UIImage(named: IMAGENAME_FROM_HTML) ?? UIImage()
let imageAttachment = NSTextAttachment(image: image)

do {
    let text = try NSMutableAttributedString(data: htmlData ?? Data(), options: options, documentAttributes: nil)
    text.addAttribute(.font, value: UIFont(name: "Arial", size: CGFloat(fontSize), range: NSMakeRange(0, text.length))
    let textWithAttachment = try NSAttributedString(attachment: imageAttachment)
    text.replaceCharacters(in: NSMakeRange(RANGE_FOR_IMAGE_IN_HTML), with: textWithAttachment)
    return text
}
catch let error {
    print(error)
    return NSMutableAttributedString(string: myString)
}

P.S. don't use semicolon on the lines end in swift.



来源:https://stackoverflow.com/questions/65635974/swift-uitextview-html-image-causes-crash-when-copy-image-is-selected-after-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!