尝试捕获iOS App屏幕快照并写入存储。我已经阅读了一些教程,并且已经确认func captureScreenshot可以正常工作,但是在尝试保存到Data时遇到了麻烦。
public static func captureScreenshot() -> UIImage{
let layer = UIApplication.shared.keyWindow!.layer
let scale = UIScreen.main.scale
// Creates UIImage of same size as view
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
layer.render(in: UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return screenshot!
}
在这里,我调用captureScreenshot方法获取UIImage并将其保存:
let localFile : UIImage = GlobalFunction.captureScreenshot()
if let image = localFile {
if let data = UIImagePNGRepresentation(image) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}
}
这是错误:
Initializer for conditional binding must have Optional type, not 'UIImage'
答案 0 :(得分:0)
消息
用于条件绑定的初始化器必须具有可选类型,而不是'UIImage'
...告诉您在这一行中您不能说if let
:
let localFile : UIImage = GlobalFunction.captureScreenshot()
if let image = localFile {
那是因为您的captureScreenshot
返回的是UIImage,而不是UIImage?
。因此,您的localFile
也是UIImage(如您的声明所述),而不是UIImage?
由于localFile
不是可选的,因此没有if let
做的可选的拆包操作。因此,您不需要中间变量localFile
。 (我不知道您为什么这么称呼它,因为UIImage不是文件。但是无论如何。)只需说
let image = GlobalFunction.captureScreenshot()
if let data = UIImagePNGRepresentation(image) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}