【问题标题】:iOS Capture Screenshot and Save to Storage [duplicate]iOS捕获屏幕截图并保存到存储[重复]
【发布时间】:2018-08-04 00:12:37
【问题描述】:

尝试截取 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'

【问题讨论】:

标签: ios swift


【解决方案1】:

消息

条件绑定的初始化器必须是 Optional 类型,而不是 'UIImage'

...告诉你不能在这一行说if let

let localFile : UIImage = GlobalFunction.captureScreenshot()
if let image = localFile {

那是因为您的 captureScreenshot 返回的是 UIImage,而不是 UIImage?。因此,您的 localFile 也是 UIImage (如您的声明所述),而不是 UIImage?

由于 localFile 不是 Optional,因此没有 Optional 可以解包,if let 就是这样做的。所以你不需要中介 localFile 变量。 (我不知道你为什么这么称呼它,因为 UIImage 不是文件。但无论如何。)只要说

let image = GlobalFunction.captureScreenshot()
if let data = UIImagePNGRepresentation(image) {
    let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
    try? data.write(to: filename)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2018-05-06
    • 2021-06-18
    相关资源
    最近更新 更多