0

How can I check if an NSAttributedString contains any NSTextAttachment's with images?

ma11hew28
  • 121,420
  • 116
  • 450
  • 651

1 Answers1

2

You can use function func enumerateAttribute(String, in: NSRange, options: NSAttributedString.EnumerationOptions = [], using: (Any?, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) to enumerate attributes NSAttachmentAttributeName and as a using: block cast the first value to NSTextAttachment and check if it has an image.

extension NSAttributedString {
    var hasImage: Bool {
        var hasImage = false
        let fullRange = NSRange(location: 0, length: self.length)

        self.enumerateAttribute(NSAttachmentAttributeName, in: fullRange, options: []) { (value, _, _) in
            print(value)
            guard let attachment = value as? NSTextAttachment else { return }

            if let _ = attachment.image {
                hasImage = true
            }
        }

        return hasImage
    }
}

let stringWithoutAttachment = NSAttributedString(string: "Some string")
print(stringWithoutAttachment.hasImage) //false

let attachment = NSTextAttachment()
attachment.image = UIImage() 

let stringWithAttachment = NSAttributedString(attachment: attachment)
print(stringWithAttachment.hasImage) //true
Mr. Hedgehog
  • 966
  • 4
  • 13