function nextTapped and function previousTapped show this error " Use of unresolved identifier 'pdfView'; did you mean 'PDFView'? " I want from function nextTapped move to next pdf page and function previousTapped move to previous pdf page when i display pdf i want from nextButton move to next pdf page and previousButton move to previous pdf page
import UIKit
import AVFoundation
import MobileCoreServices
import PDFKit
class RecorderViewController: UIViewController {
#IBOutlet var nextButton:UIButton!
#IBOutlet var previousButton:UIButton!
override func viewDidLoad() {
super.viewDidLoad()
nextButton.isHidden = true
previousButton.isHidden = true
}
#IBAction func `import`(_ sender: Any) {
let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypePDF as String], in: .import)
documentPicker.delegate = self as? UIDocumentPickerDelegate
documentPicker.allowsMultipleSelection = true
present(documentPicker, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func nextTapped(_ sender: Any) {
pdfView.goToNextPage(sender)}
#IBAction func previousTapped(_ sender: Any) {
pdfView.goToPreviousPage(sender)
}
extension RecorderViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let selectedFileURL = urls.first else {
return
}
/////////her to display PDF File
let pdfView = PDFView()
pdfView.frame = CGRect(x: 0, y: 160, width: 1024, height: 1139)
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(pdfView)
pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
let thumbnailView = PDFThumbnailView()
thumbnailView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(thumbnailView)
thumbnailView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
thumbnailView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
thumbnailView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
pdfView.bottomAnchor.constraint(equalTo: thumbnailView.topAnchor).isActive = true
pdfView.heightAnchor.constraint(equalToConstant: 150)
pdfView.displayMode = .singlePage
// Fit content in PDFView.
nextButton.isHidden = false
previousButton.isHidden = false
pdfView.autoScales = true
pdfView.document = PDFDocument(url: selectedFileURL)
let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let sandboxFileURL = dir.appendingPathComponent(selectedFileURL.lastPathComponent)
///i need to ensure the file is saved
if FileManager.default.fileExists(atPath: sandboxFileURL.path) {
print("Already exists! Do nothing")
}
else {
do {
try FileManager.default.copyItem(at: selectedFileURL, to: sandboxFileURL)
print("Copied file!")
}
catch {
print("Error: \(error)")
}
}
}
}
Define your pdfView in Class it self not in Extension like below :
//Add PDF View Object here not in extension
let pdfView = PDFView()
Just update your code slightly like this :
import UIKit
import AVFoundation
import MobileCoreServices
import PDFKit
class RecorderViewController: UIViewController {
//Add PDF View Object here not in extension
let pdfView = PDFView()
#IBOutlet var nextButton:UIButton!
#IBOutlet var previousButton:UIButton!
override func viewDidLoad() {
super.viewDidLoad()
nextButton.isHidden = true
previousButton.isHidden = true
}
#IBAction func `import`(_ sender: Any) {
let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypePDF as String], in: .import)
documentPicker.delegate = self as? UIDocumentPickerDelegate
documentPicker.allowsMultipleSelection = true
present(documentPicker, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func nextTapped(_ sender: Any) {
pdfView.goToNextPage(sender)
}
#IBAction func previousTapped(_ sender: Any) {
pdfView.goToPreviousPage(sender)
}
}
extension RecorderViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let selectedFileURL = urls.first else {
return
}
/////////her to display PDF File
pdfView.frame = CGRect(x: 0, y: 160, width: self.view.frame.size.width, height: self.view.frame.size.height - 160)
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(pdfView)
pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
let thumbnailView = PDFThumbnailView()
thumbnailView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(thumbnailView)
thumbnailView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
thumbnailView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
thumbnailView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
pdfView.bottomAnchor.constraint(equalTo: thumbnailView.topAnchor).isActive = true
pdfView.heightAnchor.constraint(equalToConstant: 150)
pdfView.displayMode = .singlePage
// Fit content in PDFView.
nextButton.isHidden = false
previousButton.isHidden = false
pdfView.autoScales = true
pdfView.document = PDFDocument(url: selectedFileURL)
let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let sandboxFileURL = dir.appendingPathComponent(selectedFileURL.lastPathComponent)
///i need to ensure the file is saved
if FileManager.default.fileExists(atPath: sandboxFileURL.path) {
print("Already exists! Do nothing")
}
else {
do {
try FileManager.default.copyItem(at: selectedFileURL, to: sandboxFileURL)
print("Copied file!")
}
catch {
print("Error: \(error)")
}
}
}
Hope this will solve your issue.
Related
I would like to implement a camera to capture portrait photos like apples default camera does. Portraiteffect and depnhdata is enabled in the PhotoSettings.
AVCapturePhotoSettings
self.output.isPortraitEffectsMatteDeliveryEnabled = true
self.output.isDepthDataDeliveryEnabled = true
photoSettings.isPortraitEffectsMatteDeliveryEnabled = true
photoSettings.isDepthDataDeliveryEnabled = true
photoSettings.embedsDepthDataInPhoto = true
photoSettings.embedsPortraitEffectsMatteInPhoto = true
printing the AVCapturePhoto.portraitEffectsMatte returns Optional(L008 2080x1170 v.1.1) but neither in my preview layer nor in the saved image is the portrait effect visible.
Additional context
AVCaptureDevice uses the builtInDualWideCamera
Printing the output.portraitEffekt logs also true
Full code:
class ViewController: UIViewController {
var session: AVCaptureSession?
var output = AVCapturePhotoOutput()
var previewLayer = AVCaptureVideoPreviewLayer()
private func setUpCamera(){
let session = AVCaptureSession()
if let device = AVCaptureDevice.default(.builtInDualWideCamera, for: .video, position: (useFrontCamera ? AVCaptureDevice.Position.front : AVCaptureDevice.Position.back)){
do {
let input = try AVCaptureDeviceInput(device: device)
if session.canAddInput(input){
session.addInput(input)
}
if session.canAddOutput(output){
session.addOutput(output)
}
previewLayer.videoGravity = .resizeAspectFill
previewLayer.session = session
session.startRunning()
self.session = session
}
catch {
print(error)
}
}
}
private func getSettings() -> AVCapturePhotoSettings{
var photoSettings = AVCapturePhotoSettings()
if(self.output.isPortraitEffectsMatteDeliverySupported && self.output.isDepthDataDeliverySupported){
self.output.isPortraitEffectsMatteDeliveryEnabled = true
self.output.isDepthDataDeliveryEnabled = true
photoSettings.isPortraitEffectsMatteDeliveryEnabled = true
photoSettings.isDepthDataDeliveryEnabled = true
photoSettings.embedsDepthDataInPhoto = true
photoSettings.embedsPortraitEffectsMatteInPhoto = true
}
return photoSettings
}
private funk takePhoto(){
self.output.capturePhoto(with: self.getSettings(), delegate: self)
}
}
extension ViewController: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
guard let data = photo.fileDataRepresentation() else { return}
let image = UIImage(data: data)
let imageView = UIImageView(image: image)
session?.stopRunning()
imageView.contentMode = .scaleAspectFill
imageView.frame = CGRect(x: 0, y: 0, width: view.frame.width/4, height: view.frame.height/4)
imageView.layer.name = "photoPreview"
view.addSubview(imageView)
UIImageWriteToSavedPhotosAlbum(image!, self, nil, nil)
}
}
```
I have a problem.
I've implemented the visionkit framework in order to detect a text when the camera is used.
The problem is that the colors of the buttons: "Keep Scan" and "Retake" are blue. I want them in black color. How can I fix this problem? I paste my code.
Thank you in advance!
import UIKit
import Vision
import VisionKit
class ScanText: UIViewController, VNDocumentCameraViewControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var TextScan: UITextView!
#IBOutlet weak var buttonStartShape: UIButton!
#IBOutlet weak var infoScattaUnaFoto: UILabel!
#IBOutlet weak var copyButtonShape: UIButton!
var textRecognitionRequest = VNRecognizeTextRequest(completionHandler: nil)
private let textRecognitionWorkQueue = DispatchQueue(label: "MyVisionScannerQueue", qos: .userInitiated, attributes: [], autoreleaseFrequency: .workItem)
var classView = ViewController()
var arrayText = String()
override func viewDidLoad() {
super.viewDidLoad()
imageView.layer.cornerRadius = 15
imageView.clipsToBounds = true
TextScan.layer.cornerRadius = 15
TextScan.clipsToBounds = true
copyButtonShape.layer.cornerRadius = 25
copyButtonShape.clipsToBounds = true
buttonStartShape.layer.cornerRadius = 25
buttonStartShape.clipsToBounds = true
TextScan.isEditable = true
setupVision()
}
#IBAction func TakePicture(_ sender: Any) {
let scannerViewController = VNDocumentCameraViewController()
scannerViewController.delegate = self
present(scannerViewController, animated: true)
}
private func setupVision() {
textRecognitionRequest = VNRecognizeTextRequest { (request, error) in
guard let observations = request.results as? [VNRecognizedTextObservation] else { return }
var detectedText = ""
for observation in observations {
guard let topCandidate = observation.topCandidates(2).first else { return }
print("text \(topCandidate.string) has confidence \(topCandidate.confidence)")
detectedText += topCandidate.string
detectedText += "\n"
}
DispatchQueue.main.async {
self.TextScan.isHidden = false
self.infoScattaUnaFoto.isHidden = true
self.copyButtonShape.isHidden = false
self.buttonStartShape.setTitle("Ripeti", for: .normal)
self.TextScan.text += detectedText
self.TextScan.flashScrollIndicators()
}
}
textRecognitionRequest.recognitionLevel = .accurate
}
private func processImage(_ image: UIImage) {
imageView.image = image
recognizeTextInImage(image)
}
private func recognizeTextInImage(_ image: UIImage) {
guard let cgImage = image.cgImage else { return }
TextScan.text = ""
textRecognitionWorkQueue.async {
let requestHandler = VNImageRequestHandler(cgImage: cgImage, options: [:])
do {
try requestHandler.perform([self.textRecognitionRequest])
} catch {
print(error)
}
}
}
func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) {
/* guard scan.pageCount >= 1 else {
controller.dismiss(animated: true)
return
}*/
for i in 0 ..< scan.pageCount {
let img = scan.imageOfPage(at: i)
processImage(img)
}
let originalImage = scan.imageOfPage(at: 0)
print(originalImage)
//let newImage = compressedImage(originalImage)
controller.dismiss(animated: true)
}
func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFailWithError error: Error) {
print(error)
controller.dismiss(animated: true)
}
func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) {
controller.dismiss(animated: true)
}
func compressedImage(_ originalImage: UIImage) -> UIImage {
guard let imageData = originalImage.jpegData(compressionQuality: 1),
let reloadedImage = UIImage(data: imageData) else {
return originalImage
}
return reloadedImage
}
//MARK: By tapping on this button, I pass all the data.
#IBAction func CopyText(_ sender: Any) {
let vc = (storyboard?.instantiateViewController(identifier: "SpeakDetail") as? ViewController)!
vc.textscannerized = TextScan.text
self.navigationController?.pushViewController(vc, animated: true)
}
}
You can try something like this:
scannerViewController.view.tintColor = .red
I am resizing a cell frame on the iPhone X to embed an instance of AVPlayerController. When i change orientation from portrait to landscape the frame size seems to change.
I end up with the controls (full screen + volume) overlapping the header and title.
Would you recommend a solution other than :
self.frame.insetBy
Here is a demo of how it looks :
iphone x demo
import UIKit
import AVKit
class VGMediaPlayerCell: VGBaseCell {
let statusBarHeight: CGFloat = 20
let contentOffset: CGFloat = 50
static let vgReuseIdentifier = "VGMediaPlayerCell"
static var playerIsPlaying: Bool = false
var toggleHeaderVisibility: Bool = false
public weak var delegate: VGMediaPlayerCellDelegate?
var moviePlayerController = AVPlayerViewController()
var waitingIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.whiteLarge)
var containerView = UIView()
var messageLabel = UILabel()
var needAutoPlay: Bool = false
var isLoaded: Bool = false
var asset: AVAsset?
var isReadyForDisplayObserver: NSKeyValueObservation?
var content: VGContent?
let deviceOrientation = UIDevice.current.orientation
//player settings
#objc var player: AVPlayer?
var PlayerViewConroller: AVPlayerViewController?
override init(frame: CGRect) {
super.init(frame: frame)
setupWaitingIndicator()
setupMessageLabel()
isReadyForDisplayObserver = moviePlayerController.observe(\.isReadyForDisplay) { [weak self] (_, _) in
guard let `self` = self else {
return
}
// When the first frame of the video is loaded, we dismiss the waiting indicator.
DispatchQueue.main.async {
if self.moviePlayerController.isReadyForDisplay {
self.waitingStateActive(isActive: false)
}
}
}
}
override func prepareForReuse() {
super.prepareForReuse()
self.isLoaded = false
needAutoPlay = false
moviePlayerController.player = nil
content = nil
asset = nil
player = nil
contextualLabel.font = nil
messageLabel.text = nil
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View creation
func setupContainerView() {
addSubview(containerView)
containerView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
containerView.leftAnchor.constraint(equalTo: leftAnchor),
containerView.rightAnchor.constraint(equalTo: rightAnchor),
containerView.topAnchor.constraint(equalTo: topAnchor),
containerView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
func setupMessageLabel() {
addSubview(messageLabel)
messageLabel.textAlignment = .center
messageLabel.textColor = .white
messageLabel.numberOfLines = 2
messageLabel.isHidden = true
messageLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
messageLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 10),
messageLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -10),
messageLabel.heightAnchor.constraint(equalToConstant: 50),
messageLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
func setupWaitingIndicator() {
addSubview(waitingIndicator)
waitingIndicator.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
waitingIndicator.centerXAnchor.constraint(equalTo: centerXAnchor),
waitingIndicator.centerYAnchor.constraint(equalTo: centerYAnchor),
waitingIndicator.widthAnchor.constraint(equalToConstant: 100),
waitingIndicator.heightAnchor.constraint(equalToConstant: 100)
])
}
// MARK: - Utils
func configurePlayer(with viewModel: VGMediaPlayerViewModel) {
//to update message label + loader
updateUI(with: viewModel)
if viewModel.error == ErrorMessage.noNetwork.rawValue {
self.stop()
}
// Create a new AVPlayer and AVPlayerLayer
guard let url = URL(string: viewModel.content?.contentURL ?? "") else { return }
self.player = AVPlayer(url: url)
// We want video controls so we need an AVPlayerViewController
PlayerViewConroller = AVPlayerViewController()
PlayerViewConroller?.player = player
PlayerViewConroller?.videoGravity = AVLayerVideoGravity.resizeAspect
insertSubview(avPlayerViewConroller!.view, at: 0)
PlayerViewConroller!.view.topAnchor.constraint(equalTo: topAnchor).isActive = true
PlayerViewConroller!.view.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
PlayerViewConroller!.view.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
PlayerViewConroller!.view.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
self.bringSubviewToFront((avPlayerViewConroller?.view!)!)
if #available(iOS 10.0, *) {
self.player?.automaticallyWaitsToMinimizeStalling = false
}
guard let asset = viewModel.avAsset else { return }
if !asset.isPlayable {
DispatchQueue.main.async {
self.waitingStateActive(isActive: false)
self.displayError(message: ErrorMessage.noPreview.rawValue)
}
}
DispatchQueue.main.async {
// Create a new AVAsset from the URL
let videoAsset = AVAsset(url: url)
// // Now we need an AVPlayerItem to pass to the AVPlayer
let videoPlayerItem = AVPlayerItem(asset: videoAsset)
// // Finally, we set this as the current AVPlayer item
self.player?.replaceCurrentItem(with: videoPlayerItem)
if self.needAutoPlay {
self.player?.play()
}
self.isLoaded = true
}
//custom insets per device orientation
// regular from for iphone 8 and downwards
// custom frame for iphone X and upwards
if UIDevice().userInterfaceIdiom == .phone {
switch UIScreen.main.nativeBounds.height {
//iPhone 5 or 5S or 5C, iPhone 6/6S/7/8, iPhone 6+/6S+/7+/8+
case 1136, 1334, 1920, 2208:
PlayerViewConroller?.view.frame = self.frame
//iPhone X, Xs, iPhone Xs Max, iPhone Xr
case 2436, 2688, 1792:
if UIApplication.shared.statusBarOrientation.isPortrait {
PlayerViewConroller?.view.frame = self.frame.insetBy(dx: 0.0, dy: 50.0)
} else if deviceOrientation == .landscapeLeft || deviceOrientation == .landscapeRight {
PlayerViewConroller?.view.frame = self.frame.insetBy(dx: 30.0, dy: 30.0)
}
default: break
}
} else {
//for the iPad
PlayerViewConroller?.view.frame = self.frame
}
//Add observer on keypath rate to monitor player's playing status
if self.toggleHeaderVisibility == true {
if UIDevice().userInterfaceIdiom == .phone {
switch UIScreen.main.nativeBounds.height {
case 2436, 2688, 1792:
player?.addObserver(self, forKeyPath: "rate", options: [.old, .new], context: nil)
default : break
}
}
}
player?.addObserver(self, forKeyPath: "rate", options: [.old, .new], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if object as AnyObject? === player {
if keyPath == "rate" {
guard let rate = player?.rate else { return }
if rate > Float(0.0) {
VGMediaPlayerCell.playerIsPlaying = true
NotificationCenter.default.post(name: .playerDidStartPlay, object: nil)
} else {
VGMediaPlayerCell.playerIsPlaying = false
NotificationCenter.default.post(name: .playerDidStop, object: nil)
}
}
}
}
func updateUI(with viewModel: VGMediaPlayerViewModel) {
messageLabel.isHidden = true
//indicating waiting state with spinner
waitingStateActive(isActive: viewModel.isLoading)
}
/**
Cancel asset loading
*/
func cancelLoading() {
asset?.cancelLoading()
}
/**
Show an error with a specific message
- parameter message: A message
*/
func displayError(message: String) {
messageLabel.text = message
messageLabel.isHidden = false
containerView.isHidden = true
}
/**
Update the waiting indicator state
- parameter active: A boolean value that indicate if the waiting indicator need to be active or not.
*/
func waitingStateActive(isActive: Bool) {
isActive ? waitingIndicator.startAnimating() : waitingIndicator.stopAnimating()
containerView.isHidden = isActive
}
}
I created window and webview programmatically.
All buttons, radiobuttons are clicked normaly.
But if I click to input and want to type text it is not clicking. Cursor changes, but focus isn't in input. Keyboard not typing.
Right button on input works fine and i can paste text in it.
//
// WindowCommand.swift
// DeskAlerts
//
// Created by mihail on 26/04/2017.
// Copyright © 2017 Toolbarstudio Inc. All rights reserved.
//
import Foundation
import Cocoa
import SINQ
import WebKit
extension NSCoder {
class func empty() -> NSCoder {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.finishEncoding()
return NSKeyedUnarchiver(forReadingWith: data as Data)
}
}
class WindowCommand:NSViewController, WebFrameLoadDelegate, WebUIDelegate, WebEditingDelegate, WebPolicyDelegate, WebDownloadDelegate, WebResourceLoadDelegate
{
var Coder: NSCoder?
var Window: NSWindow?
init() {
Coder = NSCoder.empty()
super.init(coder: Coder!)!
InitParentWindow()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func InitParentWindow()
{
let rect = NSRect.init(x: 0.0, y: 0.0, width: 500.0 , height: 500.0)
Window = NSWindow(contentRect: rect , styleMask: NSWindowStyleMask.borderless, backing: NSBackingStoreType.retained, defer: false, screen: MainScreen)
Window?.isOpaque = true
Window?.backgroundColor = NSColor.clear
Window?.hasShadow = false
Window?.isReleasedWhenClosed = true
Window?.acceptsMouseMovedEvents = true
Window?.allowsConcurrentViewDrawing = true
Window?.ignoresMouseEvents = false
Window?.isDocumentEdited = true
Window?.level = Int(CGWindowLevelForKey(.maximumWindow))
Window?.makeKeyAndOrderFront(self)
Window?.contentViewController = self
}
func Close()
{
Window?.close()
}
override func viewDidLoad() {
super.viewDidLoad()
let preferences = WebPreferences()
preferences.allowsAirPlayForMediaPlayback = true
preferences.allowsAnimatedImageLooping = true
preferences.allowsAnimatedImages = true
preferences.arePlugInsEnabled = true
preferences.autosaves = true
preferences.cacheModel = WebCacheModel.documentBrowser
preferences.isJavaEnabled = true
preferences.isJavaScriptEnabled = true
preferences.javaScriptCanOpenWindowsAutomatically = true
preferences.loadsImagesAutomatically = true
preferences.privateBrowsingEnabled = false
preferences.shouldPrintBackgrounds = false
preferences.tabsToLinks = false
preferences.usesPageCache = false
preferences.suppressesIncrementalRendering = true
self.view.frame = NSRect.init(x: 0, y: 0, width: 500, height: 500)
CaptionBrowser = WebView.init(frame: NSRect.init(x: 0, y: 0, width: 500, height: 500)
let nillvalue:WebView? = nil
if (CaptionBrowser != nillvalue)
{
CaptionBrowser?.uiDelegate = self
CaptionBrowser?.frameLoadDelegate = self
CaptionBrowser?.editingDelegate = self
CaptionBrowser?.policyDelegate = self
CaptionBrowser?.resourceLoadDelegate = self
CaptionBrowser?.downloadDelegate = self
CaptionBrowser?.windowScriptObject.setValue(HtmlInteropClass(data: Alert!, owner: self), forKey: "external")
CaptionBrowser?.preferences = preferences
self.view.addSubview(CaptionBrowser!, positioned: NSWindowOrderingMode.above, relativeTo: nil)
var url = NSURL(string: (ParentWindowParams?.captionhref)!)
CaptionBrowser?.mainFrame.load(URLRequest.init(url: (url! as URL) as URL))
let mainbrowserwidth = 480
let mainbrowserheight = 150
MainBrowser = WebView.init(frame: CGRect(x:10 ,y:150, width:480 ,height:150))
MainBrowser?.uiDelegate = self
MainBrowser?.frameLoadDelegate = self
MainBrowser?.editingDelegate = self
MainBrowser?.policyDelegate = self
MainBrowser?.resourceLoadDelegate = self
MainBrowser?.downloadDelegate = self
MainBrowser?.preferences = preferences
MainBrowser?.windowScriptObject.setValue(HtmlInteropClass(data: Alert!, owner: self), forKey: "external")
self.view.addSubview(MainBrowser!, positioned: NSWindowOrderingMode.above, relativeTo: CaptionBrowser)
let filePath = Bundle.main.path(forResource: "test", ofType: "html", inDirectory: "Resources")
url = NSURL(string: filePath!)
MainBrowser?.mainFrame.load(URLRequest.init(url: url! as URL))
//url = NSURL(string: Alerthref!)
//MainBrowser?.mainFrame.load(URLRequest.init(url: url! as URL))
}
}
func webView(_ sender: WebView!, createWebViewWith request: URLRequest!) -> WebView! {
return sender
}
func webView(_ webView: WebView!, decidePolicyForNavigationAction actionInformation: [AnyHashable : Any]!, request: URLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!)
{
listener.use()
}
func webView(_ webView: WebView!, decidePolicyForNewWindowAction actionInformation: [AnyHashable : Any]!, request: URLRequest!, newFrameName frameName: String!, decisionListener listener: WebPolicyDecisionListener!) {
listener.use()
}
func webView(_ sender: WebView!, runJavaScriptAlertPanelWithMessage message: String!, initiatedBy frame: WebFrame!) {
print(message)
}
func webView(_ sender: WebView!, runJavaScriptTextInputPanelWithPrompt prompt: String!, defaultText: String!, initiatedBy frame: WebFrame!) -> String! {
return ""
}
override func loadView() {
super.loadView()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
Found a trouble.
Window = NSWindow(contentRect: rect , styleMask: NSWindowStyleMask.borderless, backing: NSBackingStoreType.retained, defer: false, screen: MainScreen)
if I making property
styleMask: NSWindowStyleMask.borderless
Input is not availible.
I have a very basic AVFoundation Camera that has a captureButton that will take a photo and send that photo to the secondCameraController for it to be displayed. My problem is that there is a lot of iOS 10 deprecation and I'm not sure how I add in a flash when I press the captureButton. Any help will be highly appreciated. My code is below. Thank you guys.
class CameraController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
let captureSession = AVCaptureSession()
var previewLayer: CALayer!
var captureDevice: AVCaptureDevice!
var takePhoto: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
prepareCamera()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
}
let cameraView: UIView = {
let view = UIView()
view.backgroundColor = .red
return view
}()
func prepareCamera() {
captureSession.sessionPreset = AVCaptureSessionPresetPhoto
if let availableDevices = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .back).devices {
captureDevice = availableDevices.first
beginSession()
}
}
func beginSession() {
do {
let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(captureDeviceInput)
} catch {
print(error.localizedDescription)
}
if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) {
self.previewLayer = previewLayer
self.view.layer.addSublayer(self.previewLayer)
self.previewLayer.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.addSubview(captureButton)
let width: CGFloat = 85
captureButton.frame = CGRect(x: (previewLayer.frame.width / 2) - width / 2, y: (previewLayer.frame.height) - width - 25, width: width, height: 85)
captureSession.startRunning()
let dataOutput = AVCaptureVideoDataOutput()
dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString): NSNumber(value: kCVPixelFormatType_32BGRA)]
dataOutput.alwaysDiscardsLateVideoFrames = true
if captureSession.canAddOutput(dataOutput) {
captureSession.addOutput(dataOutput)
}
captureSession.commitConfiguration()
let queue = DispatchQueue(label: "com.cheekylabsltd.camera")
dataOutput.setSampleBufferDelegate(self, queue: queue)
}
}
func handleCapture() {
takePhoto = true
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
if takePhoto {
takePhoto = false
if let image = self.getImageFromSampleBuffer(buffer: sampleBuffer) {
let secondController = SecondCameraController()
secondController.takenPhoto = image
DispatchQueue.main.async {
self.present(secondController, animated: true, completion: {
self.stopCaptureSession()
})
}
}
}
}
func getImageFromSampleBuffer(buffer: CMSampleBuffer) -> UIImage? {
if let pixelBuffer = CMSampleBufferGetImageBuffer(buffer) {
let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
let context = CIContext()
let imageRect = CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(pixelBuffer), height: CVPixelBufferGetHeight(pixelBuffer))
if let image = context.createCGImage(ciImage, from: imageRect) {
return UIImage(cgImage: image, scale: UIScreen.main.scale, orientation: .right)
}
}
return nil
}
func stopCaptureSession() {
self.captureSession.stopRunning()
if let inputs = captureSession.inputs as? [AVCaptureDeviceInput] {
for input in inputs {
self.captureSession.removeInput(input)
}
}
}
lazy var captureButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .white
button.layer.cornerRadius = 42.5
button.clipsToBounds = true
button.alpha = 0.40
button.layer.borderWidth = 4
button.layer.borderColor = greenColor.cgColor
button.addTarget(self, action: #selector(handleCapture), for: .touchUpInside)
return button
}()
}
Try this code :
Swift v3.0
private func flashOn(device:AVCaptureDevice)
{
do{
if (device.hasTorch)
{
try device.lockForConfiguration()
device.torchMode = .on
device.flashMode = .on
device.unlockForConfiguration()
}
}catch{
//DISABEL FLASH BUTTON HERE IF ERROR
print("Device tourch Flash Error ");
}
}
//FOR FLASH OFF CODE
private func flashOff(device:AVCaptureDevice)
{
do{
if (device.hasTorch){
try device.lockForConfiguration()
device.torchMode = .off
device.flashMode = .off
device.unlockForConfiguration()
}
}catch{
//DISABEL FLASH BUTTON HERE IF ERROR
print("Device tourch Flash Error ");
}
}
// METHOD
//private let session = AVCaptureSession()
//MARK: FLASH UITLITY METHODS
func toggleFlash() {
var device : AVCaptureDevice!
if #available(iOS 10.0, *) {
let videoDeviceDiscoverySession = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInDuoCamera], mediaType: AVMediaTypeVideo, position: .unspecified)!
let devices = videoDeviceDiscoverySession.devices!
device = devices.first!
} else {
// Fallback on earlier versions
device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
}
if ((device as AnyObject).hasMediaType(AVMediaTypeVideo))
{
if (device.hasTorch)
{
self.session.beginConfiguration()
//self.objOverlayView.disableCenterCameraBtn();
if device.isTorchActive == false {
self.flashOn(device: device)
} else {
self.flashOff(device: device);
}
//self.objOverlayView.enableCenterCameraBtn();
self.session.commitConfiguration()
}
}
}
Swift 4
So there are two different behaviors to choose from in AVFoundation. One would be a capture device torch switch. Connect the torchSwitch action to some view and be sure to change CameraManager.shared.backDevice to your instance of the front or back device that provides the current input.
#IBAction func torchSwitch(_ sender: Any) {
guard let device = CameraManager.shared.backDevice else { return }
guard device.isTorchAvailable else { return }
do {
try device.lockForConfiguration()
device.torchMode = device.torchMode ? .off : .on
if device.torchMode == .on {
try device.setTorchModeOn(level: 0.7)
}
} catch {
debugPrint(error)
}
}
AVFoundation has deprecated device.flashMode
Now to set flash, declare a variable on camera or vc. The value here will be the default.
var flash: AVCaptureFlashMode = .off
Connect this action to some view
#IBAction func torchSwitch(_ sender: Any) { flash = flash ? .off : .on }
Then when you want to capture an image, use AVCapturePhotoOutput and prepare the photo settings. stillCameraOutput is an instance of AVCapturePhotoOutput.
let settings = AVCapturePhotoSettings()
settings.flashMode = flash
stillCameraOutput.capturePhoto(with: settings, delegate: self)
Swift 4 :
Following code is working fine for me
private enum FlashPhotoMode {
case on
case off
}
#IBOutlet weak var flashPhotoModeButton: UIButton!
#IBAction func toggleFlashPhotoMode(_ flashPhotoModeButton: UIButton ) {
sessionQueue.async {
self.flashPhotoMode = (self.flashPhotoMode == .on) ? .off : .on
let flashPhotoMode = self.flashPhotoMode
DispatchQueue.main.async {
if flashPhotoMode == .on {
self.flashPhotoModeButton.setBackgroundImage(UIImage(named: "flashON"), for: .normal)
print("flashON")
} else {
self.flashPhotoModeButton.setBackgroundImage(UIImage(named: "flashOFF"), for: .normal)
print("flashOFF")
}
}
}
}
#IBAction private func capturePhoto(_ photoButton: UIButton) {
................
.......................
if self.videoDeviceInput.device.isFlashAvailable {
if self.flashPhotoMode == .on {
photoSettings.flashMode = .on
print("FLASH ON ")
} else {
print("FLASH OFF ")
photoSettings.flashMode = .off
}
}
}
Thanks!