How do you get image data from NSAttributedString

I have an NSTextView. I insert an image into it and see it. When I get an NSTextAttachment for an NSAttributedString text view, this file wrapper is zero. How to get image data that was inserted into a text view?

I use the category in NSAttributedString to get text attachments. I would prefer not to burn to disk if possible.

- (NSArray *)allAttachments { NSError *error = NULL; NSMutableArray *theAttachments = [NSMutableArray array]; NSRange theStringRange = NSMakeRange(0, [self length]); if (theStringRange.length > 0) { NSUInteger N = 0; do { NSRange theEffectiveRange; NSDictionary *theAttributes = [self attributesAtIndex:N longestEffectiveRange:&theEffectiveRange inRange:theStringRange]; NSTextAttachment *theAttachment = [theAttributes objectForKey:NSAttachmentAttributeName]; if (theAttachment != NULL){ NSLog(@"filewrapper: %@", theAttachment.fileWrapper); [theAttachments addObject:theAttachment]; } N = theEffectiveRange.location + theEffectiveRange.length; } while (N < theStringRange.length); } return(theAttachments); } 
+7
cocoa nsattributedstring
source share
2 answers
  • List attachments. [NSTextStorage enumerateAttribute: ...]
  • Get attachment attachment file.
  • Write the URL.

     [textStorage enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, textStorage.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) { NSTextAttachment* attachment = (NSTextAttachment*)value; NSFileWrapper* attachmentWrapper = attachment.fileWrapper; [attachmentWrapper writeToURL:outputURL options:NSFileWrapperWritingAtomic originalContentsURL:nil error:nil]; (*stop) = YES; // stop so we only write the first attachment }]; 

This sample code will only write the first attachment to outputURL.

+7
source share

You can get the contained NSImage from the attachment cell.

Minimalist example:

 // assuming we have a NSTextStorage* textStorage object ready to go, // and that we know it contains an attachment at some_index // (in real code we would probably enumerate attachments). NSRange range; NSDictionary* textStorageAttrDict = [textStorage attributesAtIndex:some_index longestEffectiveRange:&range inRange:NSMakeRange(0,textStorage.length)]; NSTextAttachment* textAttachment = [textStorageAttributesDictionary objectForKey:@"NSAttachment"]; NSTextAttachmentCell* textAttachmentCell = textAttachment.attachmentCell; NSImage* attachmentImage = textAttachmentCell.image; 

EDIT: OS X only (AppKit version)

+2
source share

All Articles