質問

I have a UIWebView showing some custom HTML content. If I tap and hold, then select some text and tap the Copy option, the text gets added to UIPasteboard with the key "com.apple.rtfd". My problem now is that I can't find any way of extracting the actual textual contents of what I just copied. If I use this code:

NSString *contents = [NSString stringWithUTF8String:[data bytes]];

it returns the literal string "rtfd", regardless of what text I actually copied from the UIWebView. If I use this code:

NSString *contents = [[NSString alloc] initWithData:data 
    encoding:NSUTF8StringEncoding];

I get a blank string. How can I get the actual text contents of what I just copied into the pasteboard?

役に立ちましたか?

解決

I have learned that when you copy selected text from a UIWebView into UIPasteboard, it actually puts multiple keyed values into the dictionary returned by UIPasteboard, of which "com.apple.rtfd" is only the first key. The actual text value of the copied element is also included under the key "public.text". This code can be used to extract the value:

UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
NSArray *dataArray = [pasteboard items];
NSDictionary *dict = (NSDictionary *)[dataArray objectAtIndex:0];
NSString *pastedText;
if ([dict objectForKey:@"public.text"]) {
    // this is a text paste
    pastedText = (NSString *)[dict objectForKey:@"public.text"];
}

他のヒント

A correct Swift solution for extract rft text content what copied from Safari:

guard let rtf = textItem["public.rtf"] as? String,
        let rtfData = rtf.data(using: .utf8) else {
            return
    }
    do {
        let attr = try NSAttributedString(data: rtfData,
                                          options: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType],
                                          documentAttributes: nil)

        //DO SOMETHING ...
    }
    catch (let exc) {
        print(exc.localizedDescription)
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top