0
我有一個Cocoa應用程序,它使用WebView
加載一些頁面並截取屏幕截圖。在命令行中使用WebView:解開時發現無錯誤
Cocoa程序代碼:
class ViewController: NSViewController, WebFrameLoadDelegate {
@IBOutlet var web: WebView!
override func viewDidLoad() {
super.viewDidLoad()
web.frame = NSRect(x: 0, y: 0, width: 1024, height: 768)
web.preferences.isJavaScriptEnabled = true
web.preferences.isJavaEnabled = true
web.preferences.arePlugInsEnabled = true
web.frameLoadDelegate = self
web.mainFrame.load(URLRequest(url: URL(string: "https://google.com")!))
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func webView(_ sender: WebView!, didFinishLoadFor frame: WebFrame!) {
let queue = DispatchQueue(label: "pic")
let delay: DispatchTimeInterval = .seconds(2)
queue.asyncAfter(deadline: .now() + delay, execute: {
let data = self.web.layer?.data() // data() is a extension on CALayer
let nd = NSData(data: data!)
nd.write(toFile: "/Users/mac/Desktop/screenshot.png", atomically: true)
})
}
}
它正常工作,我得到的網頁截圖。
現在,我想到了在命令行而不是Cocoa應用程序。
命令行代碼:
class Main1: NSObject, WebFrameLoadDelegate
{
var web: WebView!
override init()
{
super.init()
web = WebView(frame: CGRect(x: 0, y: 0, width: 1024, height: 768))
web.preferences.isJavaScriptEnabled = true
web.preferences.isJavaEnabled = true
web.preferences.arePlugInsEnabled = true
web.frameLoadDelegate = self
web.shouldUpdateWhileOffscreen = true
web.mainFrame.load(URLRequest(url: URL(string: "https://google.com")!))
}
func webView(_ sender: WebView!, didFinishLoadFor frame: WebFrame!)
{
let queue = DispatchQueue(label: "pic")
let delay: DispatchTimeInterval = .seconds(2)
queue.asyncAfter(deadline: .now() + delay, execute: {
let data = self.web.layer?.data()
let nd = NSData(data: data!) // <-- The data is nil error
nd.write(toFile: "/Users/mac/Desktop/screenshot.png", atomically: true)
})
}
}
extension CALayer {
/// Get `Data` representation of the layer.
///
/// - Parameters:
/// - fileType: The format of file. Defaults to PNG.
/// - properties: A dictionary that contains key-value pairs specifying image properties.
///
/// - Returns: `Data` for image.
func data(using fileType: NSBitmapImageFileType = .PNG, properties: [String : Any] = [:]) -> Data {
let width = Int(bounds.width * self.contentsScale)
let height = Int(bounds.height * self.contentsScale)
let imageRepresentation = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)!
imageRepresentation.size = bounds.size
let context = NSGraphicsContext(bitmapImageRep: imageRepresentation)!
render(in: context.cgContext)
return imageRepresentation.representation(using: fileType, properties: properties)!
}
}
let m = Main1()
RunLoop.main.run()
我越來越fatal error: unexpectedly found nil while unwrapping an Optional value
。
爲什麼我不能在命令行中使用相同的代碼?可能是什麼原因?
如何解決?
謝謝!
P.S. CALayer
的擴展名取自here
我現在覺得很蠢,現在想念它。並感謝提示。 – ssh