When creating a UIViewControllerRepresentable for SwiftUI, how do you create a Coordinator so that it can access the delegate of a third party library?
In this case, I am trying to access BBMetal, a photo-filtering library.
This is a truncated version of the code we are trying to 'bridge' to SwiftUI:
class CameraPhotoFilterVC: UIViewController {
private var camera: BBMetalCamera!
private var metalView: BBMetalView!
private var faceView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
...
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
camera.start()
}...
}
extension CameraPhotoFilterVC: BBMetalCameraPhotoDelegate {
func camera(_ camera: BBMetalCamera, didOutput texture: MTLTexture) {
// do something with the photo
}
func camera(_ camera: BBMetalCamera, didFail error: Error) {
// In main thread
print("Fail taking photo. Error: \(error)")
}
}
Using UIViewRepresentable everything sets up properly and the CameraPhotoFilterVC works, starts up the camera, etc, but the extension does not respond. We tried to set this up as a Coordinator:
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<CameraPreviewView>) -> CameraViewController {
let cameraViewController = CameraViewController()
// Throws an error because what we really want is a BBMetalCameraPhotoDelegate
//cameraViewController.delegate = context.coordinator
return cameraViewController
}
class Coordinator: NSObject, BBMetalCameraPhotoDelegate {
var parent: CameraPreviewView
init(_ parent: CameraPreviewView) {
self.parent = parent
}
func camera(_ camera: BBMetalCamera, didOutput texture: MTLTexture) {
print("do something with the photo")
}
func camera(_ camera: BBMetalCamera, didFail error: Error) {
print("Fail taking photo. Error: \(error)")
}
}
We also tried simply leaving an extension of the ViewController:
final class CameraViewController : UIViewController {
...
}
extension CameraViewController: BBMetalCameraPhotoDelegate {
func camera(_ camera: BBMetalCamera, didOutput texture: MTLTexture) {
...
}
However the delegate methods from BBMetalCameraPhotoDelegate do not 'fire.
I suppose the question is: in UIViewControllerRepresentable or UIViewRepresentable, how do you add an "external" delegate in the makeUIViewController method?
Usually, if this was say a UIPickerView, the following line would work:
picker.delegate = context.coordinator
But in this case the delegate is 'once removed'
You need to set the BBMetalCamera's delegate at some point before you use it.
You might do it immediately after creating it. You didn't show how you create it, so I don't know if that would be a good place to set it.
You could probably just do it in viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
camera.photoDelegate = self
}
Related
I really stuck with the problem that my Today Extension widget is not fetching data from Firebase, when it's going to be appeared on screen.
So now I have:
import UIKit
import NotificationCenter
import SwiftUI
import Firebase
class TodayViewController: UIViewController, NCWidgetProviding {
#StateObject var databaseManager = TodayWidgetDatabaseManager()
#StateObject var contacts = FetchContacts() //class for fetching contacts on the phone
override func loadView() {
FirebaseApp.configure()
do {
try Auth.auth().useUserAccessGroup("test.app.id")
} catch let error as NSError {
print("Error changing user access group: %#", error)
}
if #available(iOS 10.0, *) {
self.extensionContext?.widgetLargestAvailableDisplayMode = .expanded
} else {
self.preferredContentSize = CGSize(width: 0, height: 400.0)
}
super.loadView()
}
override func viewDidLoad() {
super.viewDidLoad()
databaseManager.fetchIncomingPolls(contacts: contacts.contacts, completionHandler: {_ in})
}
override func viewWillAppear(_ animated: Bool) {
databaseManager.fetchIncomingPolls(contacts: contacts.contacts, completionHandler: {_ in})
}
#IBSegueAction func addSwiftUIView(_ coder: NSCoder) -> UIViewController? {
return UIHostingController(
coder: coder,
rootView: TodayWidgetView(databaseManager: self.databaseManager, contacts: self.contacts)
)
}
override func viewWillDisappear(_ animated: Bool) {
databaseManager.fetchIncomingPolls(contacts: contacts.contacts, completionHandler: {_ in})
}
func widgetPerformUpdate(completionHandler: (#escaping (NCUpdateResult) -> Void) = {result in return}) {
databaseManager.fetchIncomingPolls(contacts: contacts.contacts) { _ in
completionHandler(NCUpdateResult.newData)
}
}
#available(iOSApplicationExtension 10.0, *)
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
if activeDisplayMode == .expanded {
preferredContentSize = CGSize(width: maxSize.width, height: 275.0)
} else if activeDisplayMode == .compact {
preferredContentSize = maxSize
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I tried to implement fetching data in onAppear() method of SwiftUI view of the widget, also I tried to use my method for fetching data in viewDidLoad() and viewWillAppear() methods in controller. But none of this helped, so widget is only shows "Unable to load" label.
I have subclassed NSView to receive a dropped folder in order to get its URL.
I've been getting the URL to my ViewController class by accessing a property set in my custom NSView class.
import Cocoa
class DropView: NSView {
var droppedURL : URL!
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
public required init?(coder: NSCoder) {
super .init(coder: coder)
registerForDraggedTypes([NSPasteboard.PasteboardType.fileURL])
}
public override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
return NSDragOperation.copy
}
public override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
NSDragOperation.copy
}
public override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
let pboard = sender.draggingPasteboard
let urlString = pboard.string(forType: NSPasteboard.PasteboardType.fileURL)
let folderURL = URL(string: urlString!)
print(folderURL)
droppedURL = folderURL
return true
}
}
How can I let my ViewController know when a folder has been dropped onto my NSView and that a URL has been successfully captured? Is there a way other than posting a notification?
Usually you'd use delegates or closures for this. I prefer closures because they're so clean, but it's up to you.
First, define your closure in DropView:
class DropView: NSView {
var droppedURL : URL!
var droppedSuccessfully: ((URL) -> Void)? /// here!
Then, call it just like how you'd call a function. Make sure to pass in your folderURL too.
public override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
let pboard = sender.draggingPasteboard
let urlString = pboard.string(forType: NSPasteboard.PasteboardType.fileURL)
let folderURL = URL(string: urlString!)
print(folderURL)
droppedURL = folderURL
droppedSuccessfully?(folderURL) /// here!
return true
}
Finally, assign the closure back in your ViewController.
override func viewDidLoad() {
super.viewDidLoad()
...
/// prevent retain cycle
yourDropView.droppedSuccessfully = { [weak self] url in
print("URL received: \(url)")
}
}
How would I insert a button and use it to take a photo and place it in photo library. I have noticed when using arkit I cant drag buttons and place them over the view. I am seen some people online say you use snapshot() for taking the photo.
import UIKit
import SceneKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate {
#IBOutlet var sceneView: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
// Set the view's delegate
sceneView.delegate = self
// Show statistics such as fps and timing information
sceneView.showsStatistics = true
// Create a new scene
let scene = SCNScene(named: "art.scnassets/ship.scn")!
// Set the scene to the view
sceneView.scene = scene
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
// Run the view's session
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
}
I made a simple demo to show you how to combine snapshot(), ARSCNView and UIBUtton. So you may define your storyboard in this way:
as you can see, the button is inside the main view but outside and above the ARKit view
then your ViewController might be something like:
import UIKit
import ARKit
class ViewController: UIViewController {
#IBOutlet var arkitView:ARSCNView!
#IBOutlet var outputImageView:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
arkitView.session.run(ARWorldTrackingConfiguration())
}
#IBAction func takeScreenshotAction() {
outputImageView.image = arkitView.snapshot()
}
}
final result is:
I'm trying to know when a window closes, I implemented this code:
class ViewController: NSViewController, NSWindowDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let window: NSWindow? = view.window
window?.delegate = self
}
func windowWillClose(_ aNotification: Notification) {
print("windowWillClose")
}
}
Unfortunately nothing happens, what could I made wrong?
Documents: https://developer.apple.com/documentation/appkit/nswindow/1419400-willclosenotification
PS
I already read this question without to find a solution: Handle close event of the window in Swift
The problem there is that the window property will always return nil inside viewDidLoadMethod. You need to set the delegate inside viewWillAppear method:
class ViewController: NSViewController, NSWindowDelegate {
override func viewWillAppear() {
super.viewWillAppear()
view.window?.delegate = self
}
func windowWillClose(_ aNotification: Notification) {
print("windowWillClose")
}
}
in my view controller, i have set up like this.
protocol MenuDelegate {
func updateIndexOfMenuExpanded(index: Bool)
}
class ViewController: UIViewController,UITableViewDataSource, UITableViewDelegate {
var delegate : MenuDelegate?
func performaction() -> Void{
delegate!.updateIndexOfMenuExpanded(false)
}
}
and in my baseviewcontroller
class BaseViewController: UIViewController, MenuDelegate{
func updateIndexOfMenuExpanded(index: Bool){
self.menuIsExpanded = index
}
}
please help. thank you.
You have to set the delegate first.
let viewController = ViewController()
let baseViewController = BaseViewController()
viewController.delegate = baseViewController
It would also be wise to make the delegate a weak reference and to not force unwrap with !.
class ViewController: UIViewController,UITableViewDataSource, UITableViewDelegate {
weak var delegate : MenuDelegate?
func performaction() {
delegate?.updateIndexOfMenuExpanded(false)
}
}
Delegate is used when you want to pass data between viewcontrollers.this aproach is one to one
Here is the answer how to pass data using delegate
in viewcontroller
define protocol in view controller
protocol ViewController1BackClicked {
func btnBackClicked(str : String)
}
class ViewController1: UIViewController {
var strTitle : String?
var delegate : ViewController1BackClicked?
override func viewDidLoad() {
super.viewDidLoad()
if strTitle != nil{
title = strTitle
}
}
override func viewWillDisappear(animated: Bool) {
delegate?.btnBackClicked("Krutarth")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
now Protocol is created.to pass data in another view controller
viewcontroller 1 we want to access data
func btnBackClicked(str: String) {
title = str
}
output : Krutarth
this is example how to use protocol