Swift UIPasteboard not copying PNG

前端 未结 4 1023
无人共我
无人共我 2021-01-03 09:28

My problem is really odd. In the simulator the .png copies to clipboard fine and I can paste the image in the Contacts app on Simulator. But when I put the app on the phone,

4条回答
  •  有刺的猬
    2021-01-03 10:07

    There are lots of bugs and issues with the UIPasteboard class, so I'm really not surprised that you're having issues with something that so obviously is supposed to work. The documentation isn't that helpful either, to be honest. But try this; this worked for me on a physical device, and it's different to the above methods that are supposed to work but evidently don't for a bunch of people.

    guard let imagePath = NSBundle.mainBundle().pathForResource("OliviaWilde", ofType: "jpg") else
    { return }
    
    guard let imageData = NSData(contentsOfFile: imagePath) else { return }
    
    let pasteboard = UIPasteboard.generalPasteboard()
    
    pasteboard.setData(imageData, forPasteboardType: "public.jpeg")
    

    You can use either "public.jpeg" or "public.png" if the source file is .jpg; it still works. I think it only changes the format of the thing that gets pasted?

    Also, did you try adding the file extension in your first line of code where you create the UIImage? That might make it work too.

    Evidently use of this class is temperamental, not just in this use case. So even though we're doing same thing, only difference in this code is we're creating the NSData from a path rather than a UIImage. Lol let me know if that works for you.

提交回复
热议问题