title: How to implement IOServiceMatchingCallBack in Swift
body: <p>I would like to detect a specific USB is plugged in/removed in my application. For now, I can get the deviceName with this tutorial<a href="https://developer.apple.com/library/mac/documentation/DeviceDrivers/Conceptual/USBBook/USBDeviceInterfaces/USBDevInterfaces.html" rel="nofollow"> Working With USB Device Interfaces</a>. But, how can I do the callback function of (deviceAdded)<strong>IOServiceMatchingCallBack</strong> in Swift.</p>
  
  <p>I tried as follows, but I got an error: <strong>Cannot convert value of type '(UnsafePointer, iterator: io_iterator_t) -> ()' to expected argument type 'IOServiceMatchingCallback!'  </strong>
  </p>
  
  <pre><code>func detectUSBEvent() {
      var portIterator: io_iterator_t = 0
      var kr: kern_return_t = KERN_FAILURE
      let matchingDict = IOServiceMatching(kIOUSBDeviceClassName)
  
      let vendorIDString = kUSBVendorID as CFStringRef!
      let productIDString = kUSBProductID as CFStringRef!
      CFDictionarySetValue(matchingDict, unsafeAddressOf(vendorIDString), unsafeAddressOf(VendorID))
      CFDictionarySetValue(matchingDict, unsafeAddressOf(productIDString), unsafeAddressOf(ProductID))
  
      // To set up asynchronous notifications, create a notification port and add its run loop event source to the program’s run loop
      let gNotifyPort: IONotificationPortRef = IONotificationPortCreate(kIOMasterPortDefault)
      let runLoopSource: Unmanaged&lt;CFRunLoopSource&gt;! = IONotificationPortGetRunLoopSource(gNotifyPort)
      let gRunLoop: CFRunLoop! = CFRunLoopGetCurrent()
  
      CFRunLoopAddSource(gRunLoop, runLoopSource.takeUnretainedValue(), kCFRunLoopDefaultMode)
  
      // Notification of first match:
      kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification, matchingDict, deviceAdded, nil, &amp;portIterator)
      deviceAdded(nil, iterator: portIterator)
   }
  
  
  func deviceAdded(refCon: UnsafePointer&lt;Void&gt;, iterator: io_iterator_t) {
      if let usbDevice: io_service_t = IOIteratorNext(iterator)
      {
          let name = String()
          let cs = (name as NSString).UTF8String
          let deviceName: UnsafeMutablePointer&lt;Int8&gt; = UnsafeMutablePointer&lt;Int8&gt;(cs)
  
          let kr: kern_return_t = IORegistryEntryGetName(usbDevice, deviceName)
          if kr == KERN_SUCCESS {
              let deviceNameAsCFString = CFStringCreateWithCString(kCFAllocatorDefault, deviceName,
                  kCFStringEncodingASCII)
              print(deviceNameAsCFString)
              // if deviceNameAsCFString == XXX
              // Do Something
          }
  
      }
  
  }
  </code></pre>