Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an image with custom keyboard iOS

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.

like image 428
Pranav Wadhwa Avatar asked Oct 19 '22 18:10

Pranav Wadhwa


1 Answers

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>
like image 130
Ketan Saini Avatar answered Nov 15 '22 04:11

Ketan Saini