Skip to content

Instantly share code, notes, and snippets.

@matt-curtis
Created March 14, 2015 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-curtis/633f7884f12385a90b69 to your computer and use it in GitHub Desktop.
Save matt-curtis/633f7884f12385a90b69 to your computer and use it in GitHub Desktop.
HTML to Attributed String & Attributed String to HTML
#import <Foundation/Foundation.h>
@interface MCTextFormatConverter : NSObject
+ (NSString*) convertTextInResponderToHTML:(UIView<UITextInput>*)view convertSelectionOnly:(BOOL)convertSelectionOnly;
+ (NSAttributedString*) htmlToAttributedString:(NSString*)html;
@end
#import "MCTextFormatConverter.h"
typedef UIView<UITextInput> __UITextInputView;
@implementation MCTextFormatConverter
static UIWebView *_dummyWebView;
+ (void) configureWebViewDummy {
if(_dummyWebView) return;
_dummyWebView = [[UIWebView alloc] initWithFrame:(CGRect){ 0, 0, 1, 1 }];
_dummyWebView.keyboardDisplayRequiresUserAction = false;
[_dummyWebView runJS:@"document.body.contentEditable = true;"];
}
+ (void) addWebViewToViewHiearchy {
UIWindow *window = [UIApplication sharedApplication].keyWindow;
[MCTextFormatConverter configureWebViewDummy];
[window addSubview:_dummyWebView];
}
+ (NSString*) convertTextInResponderToHTML:(UIView<UITextInput>*)view convertSelectionOnly:(BOOL)convertSelectionOnly {
NSString *html;
UITextRange *formerRange = view.selectedTextRange;
BOOL wasFirstResponder = view.isFirstResponder;
if(!convertSelectionOnly || !formerRange){
view.selectedTextRange = [view textRangeFromPosition:view.beginningOfDocument toPosition:view.endOfDocument];
}
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
NSArray *formerItems = pasteboard.items;
[view copy:nil];
// ...
[self addWebViewToViewHiearchy];
[_dummyWebView runJS:@"document.body.focus()"];
[_dummyWebView paste:nil];
[_dummyWebView.superview endEditing:true];
[_dummyWebView removeFromSuperview];
//
html = [_dummyWebView runJS:@"document.body.innerHTML"];
//
[_dummyWebView runJS:@"document.body.innerHTML = ''"];
pasteboard.items = formerItems;
if(wasFirstResponder) [view becomeFirstResponder];
view.selectedTextRange = formerRange;
return html;
}
+ (NSAttributedString*) htmlToAttributedString:(NSString*)html {
NSAttributedString *attributedString =
[[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUnicodeStringEncoding]
options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
return attributedString;
}
@end
@matt-curtis
Copy link
Author

Very early (rough) implementation, but intended to show proof of concept.

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