Skip to content

Instantly share code, notes, and snippets.

@dezinezync
Last active March 1, 2019 06:49
Show Gist options
  • Save dezinezync/1b72a715203950ea39f353d75a6e644e to your computer and use it in GitHub Desktop.
Save dezinezync/1b72a715203950ea39f353d75a6e644e to your computer and use it in GitHub Desktop.
UIPasteboard Attributed Text Crash
- (void)copy:(id)sender {
// calling the following crashes the app instantly
// due to a possible bug in iOS 12.1.4.
// [super copy:sender];
NSRange range = self.selectedRange;
if (range.location != NSNotFound && range.length > 0) {
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
if (self.attributedText.length >= (range.length - range.location)) {
NSError *error = nil;
NSData *rtf = [self.attributedText dataFromRange:range
documentAttributes:@{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType}
error:&error];
if (error != nil) {
DDLogError(@"Error creating NSData from attributed text for copying to pasteboard: %@", error);
return;
}
pasteboard.items = @[@{(id)kUTTypeRTF: [[NSString alloc] initWithData:rtf encoding:NSUTF8StringEncoding],
(id)kUTTypeUTF8PlainText: self.attributedText.string}];
}
}
}
@dezinezync
Copy link
Author

temporary work-around:

@try {
    // ....
}

@catch (NSException *exc) {
    NSLog(@"Exception when copying attributed text: %@", exc);
    
    pasteboard.string = [[self text] substringWithRange:range];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment