SnapshotService.swift 951 Bytes
//
//  SnapshotService.swift
//  browser
//
//  Created by Artem Talko on 23.10.2023.
//

import UIKit
import WebKit


final class SnapshotService {
    static let shared = SnapshotService()
    let snapshotConfiguration = WKSnapshotConfiguration()
    
    func makeSnapshot(_ viewForSnap: UIView) -> UIImage {
        let renderer = UIGraphicsImageRenderer(size: viewForSnap.bounds.size)
        let siteSnapshotImage = renderer.image { (context) in
            viewForSnap.layer.render(in: context.cgContext)
        }
        return siteSnapshotImage
    }
    
    func makeWKWebViewSnapshot(_ wkWV: WKWebView?, completion: @escaping (UIImage?) -> Void) {
        wkWV?.takeSnapshot(with: snapshotConfiguration) { (image, error) in
            if let snaphotIMG = image {
                completion(snaphotIMG)
            } else if let error = error {
                print(error)
                completion(nil)
            }
        }
    }
}