5

I am building my first custom keyboard. I am using Swift 2 and Xcode 7. I have this as my keyboard

Keyboard

(I am running it on my iPhone) When I tap the little alien face, I would like to have either

  1. a little emoji with that image or

  2. insert the image (if possible) to where the user is typing. I have tried this code

    let pasteboard: UIPasteboard = UIPasteboard.generalPasteboard()
    let image: UIImage = currentImage!
    let newImage = scaleImage(image, toSize: CGSize(width: 40, height: 40))
    let imgData: NSData = UIImagePNGRepresentation(newImage)!
    pasteboard.setData(imgData, forPasteboardType: UIPasteboardTypeListImage[0] as! String)
    
    let proxy = UITextDocumentProxy.self as! UITextDocumentProxy
    let data = pasteboard.string!
    print(data)
    proxy.insertText(data)
    

but I have been unsuccessful. When I print(data), I receive nil, followed by an EXC_BAD_ACCESS on the next line. How can I achieve either of the 2 goals I had? Thanks for your help.

Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61
  • Did you ever find a solution for this? – rain2o Mar 10 '16 at 17:00
  • No. Somebody posted an answer earlier, and we were discussing it in the comments. I asked him a question and he never replied. I guess he deleted his post. Do you have a solution? – Pranav Wadhwa Mar 10 '16 at 18:34
  • 1
    After some additional research I found this - http://stackoverflow.com/a/25827906/3489599. It's a little old, so this might have changed since then, but as of right now that is the only thing I have found to answer the question. Unfortunately, that answer is No. – rain2o Mar 10 '16 at 18:56
  • I'm also having the same problem did u find any solution for this? – Ramakrishna Oct 07 '16 at 13:05
  • 1
    No :( However, I have found that most iOS keyboards with images tend to copy the image to the clipboard then tell the user to paste it. I believe this is the only workaround to this as of now – Pranav Wadhwa Oct 07 '16 at 13:08
  • Do you have any solution for this, @PranavWadhwa ? Please help me with the same issue. – Cu'i Bap Feb 27 '20 at 04:01

1 Answers1

3

For Swift 5:

import MobileCoreServices

guard
    let newImage = UIImage(named: "yourImage.png"),
    let imgData = newImage.pngData()
else { return }

UIPasteboard.general.setData(imgData, forPasteboardType: kUTTypePNG as String)

Also set your keyboard extension info.plist to:

<dict>
    <key>IsASCIICapable</key>
    <false/>
    <key>PrefersRightToLeft</key>
    <false/>
    <key>PrimaryLanguage</key>
    <string>en-US</string>
    <key>RequestsOpenAccess</key>
    <true/>
</dict>
Witek Bobrowski
  • 3,749
  • 1
  • 20
  • 34