iOS捕获屏幕截图并保存到存储
正在尝试捕获iOS应用程序的屏幕截图并写入存储。我已经阅读了一些教程,我已经确认func captureScreenshot可以工作,但是在保存数据时遇到了问题iOS捕获屏幕截图并保存到存储,ios,swift,Ios,Swift,正在尝试捕获iOS应用程序的屏幕截图并写入存储。我已经阅读了一些教程,我已经确认func captureScreenshot可以工作,但是在保存数据时遇到了问题 public static func captureScreenshot() -> UIImage{ let layer = UIApplication.shared.keyWindow!.layer let scale = UIScreen.main.scale // Creates UIImag
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!
}
在这里,我调用CaptureShreenshot方法来获取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'
信息
条件绑定的初始值设定项必须具有可选类型,而不是“UIImage”
…告诉您,如果让在这行中:
let localFile : UIImage = GlobalFunction.captureScreenshot()
if let image = localFile {
这是因为您的捕获截图
返回的是UIImage,而不是UIImage?
。因此,您的localFile
也是一个UIImage(正如您的声明所述),而不是UIImage?
由于localFile
不是可选的,因此没有可选择的展开选项,这就是如果let执行的操作。因此,您不需要中介localFile
变量。(我不知道你为什么这么叫它,因为UIImage不是一个文件,但不管怎样。)只要说
let image = GlobalFunction.captureScreenshot()
if let data = UIImagePNGRepresentation(image) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}
试试这个