我的问题真的很奇怪。在模拟器中,.png 可以很好地复制到剪贴板,我可以将图像粘贴到模拟器上的联系人应用程序中。但是当我将应用程序放在手机上时,png 不会复制到剪贴板。
let img = UIImage(named: "myimage")
let data = NSData(data: UIImagePNGRepresentation(img) )
UIPasteboard.generalPasteboard().setData(data, forPasteboardType: "public.png")
那是我正在使用的代码,但正如我所说,它不会复制到剪贴板。我在键盘上下文中使用此代码,尽管在复制到剪贴板时这无关紧要。如果有人有任何想法,请告诉我。提前致谢!哦,这是我在 Swift 中的第一个应用程序,也是我的第一个 iOS 应用程序,所以我没有丰富的经验来判断这是 Swift 问题还是我遗漏了什么。 =\
最佳答案
确保代码在您的主机应用(而非键盘扩展应用)中运行良好。 例如,检查读取的图像是否具有相同的分辨率:
//the Pasteboard is nil if full access is not granted
let pbWrapped: UIPasteboard? = UIPasteboard.generalPasteboard()
if let pb = pbWrapped {
var type = UIPasteboardTypeListImage[0] as! String
if (count(type) > 0) && (image != nil) {
pb.setData(UIImagePNGRepresentation(image), forPasteboardType: type)
var readDataWrapped: NSData? = pb.dataForPasteboardType(type)
if let readData = readDataWrapped {
var readImage = UIImage(data: readData, scale: 2)
println("\(image) == \(pb.image) == \(readImage)")
}
}
}
如果键盘应用程序中的粘贴板对象为nil
,这意味着您没有提供对键盘的完全访问权限:Copying and pasting image into a textbook in simulator
关于Swift UIPasteboard 不复制 PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25912668/