How do I get a String from UIPasteboard.value(forPasteboardType: kUTTypePlainText)?

722 Views Asked by At

The documentation for UIPasteboard.value(forPasteboardType:) says, "For example, if the representation type is kUTTypePlainText … the method returns an NSString object".

However, on my phone, UIPasteboard.general.value(forPasteboardType: kUTTypePlainText as String) as? String is nil. It appears to return Data. So I made my code more elaborate:

if let text = value as? String {
    return text
} else if let data = value as? Data {
    return String(data: data, encoding: String.Encoding.utf8)
}

If I copy plain text from a text field in a Swift app, it falls into the second code path, and returns the text as expected. But if I, for example, open Twitter and copy the link to a tweet, it falls into the second code path and String.init(data:encoding:) returns nil.

Am I misusing UIPasteboard? I thought that if you asked for text, it would give you text, but it doesn't seem to be filtering at all if I'm getting something other than UTF-8 from Twitter.

The app is built with Xcode 12.5 running on iOS 14.4.2.

0

There are 0 best solutions below