Radagast the Brown Radagast the Brown - 6 months ago 21
Swift Question

Google Nearby for Swift - How discovery Audio only?

I am using Google's Nearby and trying to use discoveryMediums Audio (only) without using BLE or Classic BT. The reason is because I want discovery to happen in a room and not bleed through walls. Currently I have this code. If I turn off BT on an iPhone running the app I'm informed it's required for Nearby to work. I must be missing something rudimentary.

func startSharingWithName(name: String) {
if let messageMgr = self.messageMgr {
// Show the name in the message view title and set up the Stop button.
messageViewController.title = name

// Publish the name to nearby devices.
let pubMessage: GNSMessage = GNSMessage(content: name.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: true))
publication = messageMgr.publicationWithMessage(pubMessage)

// Subscribe to messages from nearby devices and display them in the message view.

let params: GNSSubscriptionParams = GNSSubscriptionParams.init(strategy:
GNSStrategy.init(paramsBlock: { (params: GNSStrategyParams!) -> Void in
params.discoveryMediums = .Audio
params.includeBLEBeacons = false
}))

subscription = messageMgr.subscriptionWithParams(params,
messageFoundHandler:{[unowned self] (message: GNSMessage!) -> Void in
self.messageViewController.addMessage(String(data: message.content, encoding:NSUTF8StringEncoding))
},
messageLostHandler: {[unowned self](message: GNSMessage!) -> Void in
self.messageViewController.removeMessage(String(data: message.content, encoding: NSUTF8StringEncoding))
})
}
}`

Answer

You need to pass the GNSStrategy object to both the subscription and the publication. As you've coded it, the publication is still using both BLE and audio.

I would also recommend moving away from the non-deprecated methods that create publications/subscriptions. Try this:

  let strategy = GNSStrategy.init(paramsBlock: { (params: GNSStrategyParams!) -> Void in
      params.discoveryMediums = .Audio
  })

  publication = messageMgr.publicationWithMessage(pubMessage, paramsBlock: { (pubParams: GNSPublicationParams!) in
    pubParams.strategy = strategy
  })

  subscription = messageMgr.subscriptionWithMessageFoundHandler({[unowned self] (message: GNSMessage!) -> Void in
    self.messageViewController.addMessage(String(data: message.content, encoding:NSUTF8StringEncoding))
  }, messageLostHandler: {[unowned self](message: GNSMessage!) -> Void in
    self.messageViewController.removeMessage(String(data: message.content, encoding: NSUTF8StringEncoding))
  }, paramsBlock: { (subParams: GNSSubscriptionParams!) -> Void in
      subParams.strategy = strategy
  })