New to Swift and iOS. I am attempting to allow the user to copy an nsattributedstring in my app and paste it into Mail, iMessage, or whatever app they choose.
@IBAction func action(sender: UIButton!) {
let stringAttributes = [
NSFontAttributeName: UIFont.boldSystemFontOfSize(14.0),
NSBackgroundColorAttributeName: UIColor.redColor(),
]
let attributedString = NSMutableAttributedString(string: "Hello world!", attributes: stringAttributes)
do {
let documentAttributes = [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType]
let rtfData = try attributedString.dataFromRange(NSMakeRange(0, attributedString.length), documentAttributes: documentAttributes)
if let rtfString = String(data: rtfData, encoding: NSUTF8StringEncoding) {
let pb = UIPasteboard.generalPasteboard()
return pb.string = rtfString
}
}
catch {
print("error creating RTF from Attributed String")
}
}
When pasted, this returns:
Hello world!{ NSBackgroundColor = "UIDeviceRGBColorSpace 1 0 0 1";NSFont = " font-family:\".SFUIText-Semibold\"; font-weight: bold; font-style: normal; font-size: 14.00pt"; }
Edited code returns:
{\rtf1\ansi\anscipg1252{fontal\f0\fnil\fcharset0 .SFUIText-Semibold;}{\colortbl;\red255\green255\blue255;\red255\green0\blue0;}\pard\tx560\tx1120\tx1680...\pardirnatural\partightenfactor0 \f0\b\fs28\cf0 Hello world!
While doing research, I came across this answer but was not able to get it to work from Leonard Pauli's response. Maybe because that's only within the app and not pasting to another? I'm sorry if this is a duplicate of this question. Paste Formatted Text, Not Images or HTML
I also could not translate this Copy Text with Formatting - iOS 6 NSAttributedString to Pasteboard to swift
I can paste plain text just not text with any attributes.