swift nearby api doesn't find beacons - ios

I want to use my swift ios app to scan for beacons using google nearby api (not iBeacon api)
I saw Google developer doc, and I took the git sample from the same site.
Here is my code
I have installed the app on a real ios device for the first time
but the found and lost handlers are never called.
I doubled checked the bundle id, the public ios API key (same google console project of the beacon attachment)
but it still doesn't work near a working and registered beacon.
I also have an android app which succeeds in scanning the same beacon.
What else can I check?
I'm missing the "Strategy" piece of code in my swift code.
How can I add this? Why is this missing in the github example?
GNSStrategy *beaconStrategy = [GNSStrategy
strategyWithParamsBlock:^(GNSStrategyParams *params) {
params.includeBLEBeacons = YES;
}];
GNSSubscriptionParams *beaconParams = [GNSSubscriptionParams
paramsWithMessageNamespace:#"com.mycompany.mybeaconservice"
type:#"mybeacontype"
strategy:beaconStrategy];
_beaconSubscription = [_messageManager subscriptionWithParams:beaconParams
messageFoundHandler:myMessageFoundHandler
messageLostHandler:myMessageLostHandler];
in my code:
func startScanning() {
if let messageMgr = self.messageMgr {
// Subscribe to messages from nearby devices and display them in the message view.
subscription = messageMgr.subscriptionWithMessageFoundHandler({[unowned self] (message: GNSMessage!) -> Void in
self.mainViewController.location_text.text = (String(data: message.content, encoding:NSUTF8StringEncoding))
self.mainViewController.startRefreshTimer()
},
messageLostHandler: {[unowned self](message: GNSMessage!) -> Void in
if (self.mainViewController.userState.enrollState == EnrollState.confirmPosition)
{
self.mainViewController.stopRefreshTimer()
self.mainViewController.enrollButtonManager.setSearchingForBeaconsBtn()
}
})
}
}

You'll need to add the GNSStrategy to your subscription, which lets you enable beacon scanning. Try this:
let params: GNSSubscriptionParams = GNSSubscriptionParams.init(strategy:
GNSStrategy.init(paramsBlock: { (params: GNSStrategyParams!) -> Void in
params.includeBLEBeacons = true;
}))
subscription = messageMgr.subscriptionWithParams(params,
messageFoundHandler:{[unowned self] (message: GNSMessage!) -> Void in
self.mainViewController.location_text.text = (String(data: message.content, encoding:NSUTF8StringEncoding))
self.mainViewController.startRefreshTimer()
},
messageLostHandler: {[unowned self](message: GNSMessage!) -> Void in
if (self.mainViewController.userState.enrollState == EnrollState.confirmPosition) {
self.mainViewController.stopRefreshTimer()
self.mainViewController.enrollButtonManager.setSearchingForBeaconsBtn()
}
})
Beacon scanning is off by default because iOS presents the user with the location permission dialog when beacon scanning is first turned on, and this is unacceptable for apps that use the Nearby library but don't scan for beacons.
Thanks for the feedback about the github example not showing how to scan for beacons. I'll see about adding it.

Related

IOS 13 doesn't play a notification sound using FirebasePushNotificationPlugin

I use Firebase to push notifications to the users at a certain time. They receive the notification but no alert sound is played. In the settings, the allow sound/notifications are turned on and other IOS13 and other apps play sound.
Version Number of FirebasePushNotificationPlugin Plugin: 3.3.10
Device Tested On: iphone X, OS: 13.4.1
Simulator Tested On: N/A (simulators don't receive notifications)
Version of VS: VS for Mac Community, 8.6.6 (build 11)
Version of Xamarin: Xamarin.IOS 13.18.2.1, Xamarin.Forms v4.6.0.847
AppDelegate.cs:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
bool fbaseStarted = false;
try
{
// This method does all the UNUserNotificationCenter.Current.RequestAuthorization() code so we don't have to.
FirebasePushNotificationManager.Initialize(options, true);
fbaseStarted = true;
}
catch
{ }
LoadApplication(new App());
if (!fbaseStarted)
{
try
{
FirebasePushNotificationManager.Initialize(options, true);
}
catch { }
}
FirebasePushNotificationManager.CurrentNotificationPresentationOption = UNNotificationPresentationOptions.Badge | UNNotificationPresentationOptions.Alert | UNNotificationPresentationOptions.Sound;
}
Within one of the pages of my code, I subscribe a list of tags (please note that I unsubscribe because the first time the code runs it fails silently if the notifications aren't approved - resulting in the model thinking the notifications was subscribed when it wasn't):
CrossFirebasePushNotification.Current.UnsubscribeAll();
CrossFirebasePushNotification.Current.Subscribe(Constants.NotificationTagsArray);
I keep coming across payload json solutions but unless I am wrong, I don't think that applies to me as I am using Xamarin and the FirebasePushNotificationPlugin. Is there any additional permissions that were added in ios 13 for playing notifications with sound that I have missed?
I have also posted here: https://github.com/CrossGeeks/FirebasePushNotificationPlugin/issues/348 but nobody has been able to assist me yet.
Thanks
The issue actually lies with the sending of the notifications nothing to do with the Xamarin App. The issue resided in the services that sends the notifications to firebase (to then be sent out to the phones).
In the service we were sending a FirebaseNet.Messaging.Message() to the phones:
Message FireBasemessage = new Message()
{
To = "/topics/" + PushNote.Tag,
TimeToLive = 86400,
Priority = MessagePriority.high,
ContentAvailable = true,
Notification = new AndroidNotification()
{
Tag = "/topics/" + PushNote.Tag,
Body = enhancedMessage,
Title = xtitle,
}
,
Data = new Dictionary<string, string>
{
{ "param", PushNote.Tag },
{ "text", enhancedMessage}
}
};
In the AndroidNotification() object required Sound = "default" to be added for it to work. Please note that this works for both Android and IOS notifications despite the fact it is an AndroidNotification object.

Beacons array is empty in didRangeBeaconsInRegion event in ionic ios app

im using ionic native ibeacon library to detect beacons.I can detect beacons with android but when I try in ios ,i always see an empty beacon array.
I tried these things ,but still cant see the beacons in ios (device is iphone 6s plus 11.4.1) (bluetooth service is enabled on device)
I tried both requestWhenInUseAuthorization and also
requestAlwaysAuthorization.
I add NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription key in info.plist
my code is like this, its working on android device
import { Injectable } from '#angular/core';
import { Platform, Events } from 'ionic-angular';
import { IBeacon } from "#ionic-native/ibeacon";
#Injectable()
export class BeaconProvider {
delegate: any;
region: any;
constructor(
public platform: Platform,
public events: Events,
private iBeacon: IBeacon
) {
this.initialise();
}
initialise(): any {
let promise = new Promise((resolve, reject) => {
if (this.platform.is("cordova")) {
this.iBeacon.requestAlwaysAuthorization();
// ALSO try this one too this.iBeacon.requestWhenInUseAuthorization();
this.delegate = this.iBeacon.Delegate();
this.delegate.didRangeBeaconsInRegion().subscribe(
data => {
this.events.publish("didRangeBeaconsInRegion", data);
//console.log("didRangebeacons__" + JSON.stringify(data)); // empty beacons array
},
error => console.error()
);
this.region = this.iBeacon.BeaconRegion("deskBeacon", "e2c56db5-dffb-48d2-b060-d0f5a71096e0");
this.iBeacon
.startRangingBeaconsInRegion(this.region)
.then(
() => {
resolve(true);
},
error => {
console.error("Failed to begin monitoring: ", error);
resolve(false);
}
);
} else {
resolve(false);
}
});
return promise;
}
}
EDIT
My location services are on ,and I'm using same uuid in ios or android (ionic,same code).By the way I tried to make a iphone as beacon transmitter by an app in market,other iphone can see it as beacon.
And here is the screenshot of beacon scope app
A few things to check on iOS:
Go to settings, location, and check if your app has been granted location permission.
Make sure Bluetooth is turned on
Try a 3rd party beacon scanner like Locate Beacon, configure it with your UUID and make sure it can detect your beacon with the same device.
EDIT: A few more steps
Make sure iOS has Location turned on in Settings (the overall setting, not just for your app) Settings -> Privacy -> Location Services
Since you can detect on Android but not iOS, double check the UUID that you see on Android and make sure it matches exactly what you enter on iOS.
If the UUID in the config matches, but it still won't detect, verify that the beacon is actually sending out an iBeacon frame and not AltBeacon or some format iPhone won't see by default. If you use the Beacon Scope app for Android, it will tell you the frame type.

Can use DJI SDK to replicate "Pitch Lock" feature of DJI Go app?

I'm trying to replicate the "Pitch Lock" on / off feature of the DJI Go app. How can I do this?
I'm using XCode 8.2.1, building for iOS 10.1, connecting to an Osmo Mobile with an iPhone 6s attached. The Osmo Mobile has the latest firmware (version 01.30.01.52).
Everything works so far (registerApp, connecting via bluetooth, getting handheld button presses, getting gimbal battery updates, getting gimbal updates).
Setting setGimbalWorkMode to either .freeMode or .yawFollowMode doesn't seem to have any effect. No error is returned in the completion block, but there's no effect on Gimbal operation.
The gimbal behaves as if it is in .freeMode (always moves to the exact direction handheld stick is pointing), but DJIGimbalDelegate only receives .yawFollowMode updates (which is what the pitchLock mode should do).
Setting setGimbalWorkMode to other modes results in an error (as expected with Osmo Mobile device).
Here's how I'm trying to toggle pitchLock on/off.
#IBAction func pitchLockPressed(_ sender: UIButton) {
pitchLock = !pitchLock
if let gimbal = fetchGimbal() {
var workMode : DJIGimbalWorkMode = .freeMode // .freeMode .fpvMode and .unknown return error using Osmo Mobile
if pitchLock {
workMode = .yawFollowMode
}
gimbal.setGimbalWorkMode(workMode, withCompletion: { (error) in
if (error != nil) {
print("error workMode: \(error?.localizedDescription)")
self.pitchLock = !(self.pitchLock) // back to previous
}
})
}
}
Here's the delegate, which only reports .yawFollowMode no matter what I do:
func gimbal(_ gimbal: DJIGimbal, didUpdate gimbalState: DJIGimbalState) {
// var needUpdate = false
if lastReportedWorkMode != gimbalState.workMode {
lastReportedWorkMode = gimbalState.workMode
switch lastReportedWorkMode {
case DJIGimbalWorkMode.fpvMode:
print("FPV\n")
case DJIGimbalWorkMode.freeMode:
print("Free\n")
case DJIGimbalWorkMode.yawFollowMode:
print("Yaw-follow\n")
case DJIGimbalWorkMode.unknown:
print("Unknown\n")
}
}
Anyone getting setGimbalWorkMode to actually change gimbal modes?

Call blocking feature in iOS 10

I am trying to integrate CallDirectory Extension for blocking some incoming call. But application is not even recognising the numbers provided for blocking. Is there anyone who have succeeded in doing this ??
You can see the format that i have used..
private func addIdentificationPhoneNumbers(to context: CXCallDirectoryExtensionContext) throws {
let phoneNumbers: [CXCallDirectoryPhoneNumber] = [ 18775555555, 18885555555,+91949520]
let labels = [ "Telemarketer", "Local business","myPhone"]
for (phoneNumber, label) in zip(phoneNumbers, labels) {
context.addIdentificationEntry(withNextSequentialPhoneNumber: phoneNumber, label: label)
}
}
And , i referred this for development. http://iphoneramble.blogspot.in/2016/07/ios-10-callkit-directory-extension.html
Testing Device & iOS Version - iphone 5s ,iOS 10.1
Atlast , I have got the solution for call blocking. I haven't had a way to check if the call blocking code is working or not. Here are some of the things that i have done for making it work.
Check if your application is running in 64 bit iOS device
(iphone 5s or greater devices)
Adding the numbers in numerically ascending order
Add country code to every number
A sample code for adding mobile numbers for blocking is given below
let phoneNumber : CXCallDirectoryPhoneNumber =
CXCallDirectoryPhoneNumber("+9194******")!
context.addBlockingEntry(withNextSequentialPhoneNumber: phoneNumber)
Check your application has given permission to black calls
(setting -> phone -> call Blocking & identification -> Check your app is allowed to block calls)
You can also check the enabledStatus by putting this below code in your viewController
CXCallDirectoryManager.sharedInstance.getEnabledStatusForExtension(withIdentifier:
"bundleIdentifierOfYourExtension", completionHandler:
{(status, error) -> Void in
if let error = error {
print(error.localizedDescription)
}
})
Also , add following code to viewController
CXCallDirectoryManager.sharedInstance.reloadExtension(withIdentifier:
“bundleIdentifierOfYourExtension”, completionHandler: { (error) -> Void in
if let error = error {
print(error.localizedDescription)
}
})
You will find these url's helpful for the development.
http://iphoneramble.blogspot.in/2016/07/ios-10-callkit-directory-extension.html
https://translate.google.com/translate?hl=en&sl=zh-CN&u=http://colin1994.github.io/2016/06/17/Call-Directory-Extension-Study/&prev=search
Kindly please let me know if you have got improved methods and corrections.
Thanks and happy coding.
Good to see Apple listening to enhancement requests with CX. With iOS 13.4, Apple added the ability to open Call Blocking & Identification settings directly from the app.
func openSettings(completionHandler completion: ((Error?) -> Void)? = nil)
https://developer.apple.com/documentation/callkit/cxcalldirectorymanager/3521394-opensettings
The array of phone numbers must be a sorted list of int64's. From smallest to largest. The list will be rejected with an "entries out of order" error otherwise.

Google Nearby API on iOS background scanning

I've got the Nearby API set up in my Swift app and I can receive messages when the app is in the foreground. Following the instructions in the docs
I try to include params.allowInBackground = true in the appropriate place but I get an error:
Value of type 'GNSBeaconStrategyParams' has no member 'allowInBackground'
So, I can't do that and my GNSSubscription object looks like this:
subscription = messageManager.subscriptionWithMessageFoundHandler(
messageFoundHandler, messageLostHandler: messageLostHandler,
paramsBlock: { (params: GNSSubscriptionParams!) in
params.deviceTypesToDiscover = .BLEBeacon
params.permissionRequestHandler = { (permissionHandler: GNSPermissionHandler!) in
// TODO: Show custom dialog here, and call permissionHandler after it is dismissed
// show the dialogue
}
params.beaconStrategy = GNSBeaconStrategy(paramsBlock: { (params: GNSBeaconStrategyParams!) in
params.includeIBeacons = true
//params.allowInBackground = true //*** THIS DOESN'T WORK ***
})
})
My messageHandlers look like this:
messageFoundHandler = {[unowned self](message: GNSMessage!) -> Void in
print("Found handler:", message.type, "->", String(data: message.content!, encoding:NSUTF8StringEncoding)!)
if UIApplication.sharedApplication().applicationState != .Active {
let localNotification = UILocalNotification()
localNotification.alertBody = "Message received" + String(data: message.content!, encoding:NSUTF8StringEncoding)!
UIApplication.sharedApplication().presentLocalNotificationNow(localNotification)
}
}
messageLostHandler = {(message: GNSMessage!) -> Void in
print("Lost Handler:", message.type, "->", String(data: message.content, encoding:NSUTF8StringEncoding)!)
}
With this set up and an Eddystone beacon in range I now get notifications in the background! Since this is what I want I should be happy. However, if I leave the device connected to xcode with the app in the background I start to see a stream of messages like this (seems to be roughly every 5 seconds):
2016-07-23 19:35:08.243 Hoc[1269:622746] Can't endBackgroundTask: no background task exists with identifier 2f3, or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.
I'm using v0.10.0 of NearbyMessages. If anyone can point me in the right direction to get background scanning working reliably on iOS that would be great.
This was caused by an issue with Cocoapods. Even though I used $ pod update and similar approaches to remove/re-added the NearbyMessages cocoaPod from my project, for some reason I couldn't get the latest version (1.0.1) of the Nearby SDK installed. The solution was to manually download the spec from Github and overwrite the files in ~/.cocoapods/repos/master.
Then to make sure I had the latest version installed, I changed my podfile to include pod 'NearbyMessages', '~> 1.0.1' which worked.
Now I can set the appropriate params on the GNSBeaconStrategy object and background scanning for Eddystone beacons works in the background on iOS. :-)
I hope this helps.

Resources