【发布时间】: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'
【问题讨论】: