Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/118.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
iOS捕获屏幕截图并保存到存储_Ios_Swift - Fatal编程技术网

iOS捕获屏幕截图并保存到存储

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

正在尝试捕获iOS应用程序的屏幕截图并写入存储。我已经阅读了一些教程,我已经确认func captureScreenshot可以工作,但是在保存数据时遇到了问题

    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)
}
试试这个