Swift Event Callbacks

Supporting 10.7 and up
chrisr
Fresh meat
Posts: 2
Joined: Thu Sep 22, 2016 9:13 pm
Contact:

Swift Event Callbacks

Postby chrisr » Tue Oct 04, 2016 10:07 pm

I am trying to convert the Objective-C PhidgetInterfaceKitController class to swift but am having trouble with the event handlers.

Could you provide an example in Swift on how to do the CPhidget_set_OnAttach_Handler for instance?

-Chris

LucasP
Phidgetly
Posts: 17
Joined: Fri Oct 07, 2016 4:47 pm
Contact:

Re: Swift Event Callbacks

Postby LucasP » Fri Oct 07, 2016 4:52 pm

Here is some code:

Code: Select all

import UIKit

let gotAttach: @convention(c)(CPhidgetHandle?, UnsafeMutableRawPointer?) ->(Int32) = {phid,context in
    DispatchQueue.main.async(execute: {
        let myObject = Unmanaged<ViewController>.fromOpaque(context!).takeUnretainedValue()
        myObject.phidgetAdded()
    })
    return EPHIDGET_OK
}

class ViewController: UIViewController {
    var phidget:CPhidgetFrequencyCounterHandle? = nil
   
    func bridge<T : AnyObject>(_ obj : T) -> UnsafeMutableRawPointer {
        return Unmanaged.passUnretained(obj).toOpaque()
    }
   
    override func viewDidLoad() {
        super.viewDidLoad()
        CPhidgetFrequencyCounter_create(&phidget)
        CPhidget_set_OnAttach_Handler(phidget, gotAttach, bridge(self))
        CPhidget_openRemote(phidget, -1, "Lucas-PC", "")
    }

    func phidgetAdded(){
        print("\n\nPhidget Frequency Counter added\n\n")
    }
}


Return to “macOS”

Who is online

Users browsing this forum: No registered users and 1 guest