0
#import "NearbyHandler.h"
#import <GNSMessages.h>

static NSString * const kMyAPIKey = @"********";

@interface NearbyHandler ()
@property(nonatomic) GNSPermission *nearbyPermission;
@property(nonatomic) GNSMessageManager *messageMgr;
@property(nonatomic) id<GNSPublication> publication;
@property(nonatomic) id<GNSSubscription> subscription;
@end

@implementation NearbyHandler


- (instancetype)init
{
    if (self = [super init])
    {
        [self configureNearbyFramework];
    }
    return self;
}

- (void)configureNearbyFramework
{
    __weak __typeof__(self) weakSelf = self;
    _nearbyPermission = [[GNSPermission alloc] initWithChangedHandler:^(BOOL granted) {

        __strong __typeof(weakSelf) strongSelf = weakSelf;

        if(strongSelf)
        {
            NSLog(@"Nearby Permission:%@", granted ? @"YES" : @"NO");
        }

    }];

    [GNSMessageManager setDebugLoggingEnabled:YES];

}

#pragma mark - START_SCAN_PUBLISH_METHODS
- (void)startPublishingDefaultData
{

    NSDictionary *dataDict = @{@"device_name":@"cefgrstd"};
    NSError *error = nil;
    NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dataDict
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:&error];

    if(!error)
    {
        [self pusblishData:dataFromDict];
    }

}

- (void)publishSpecificData:(NSString *)stringData
{
    if(stringData.length)
    {
        NSData *pubData = [stringData dataUsingEncoding:NSUTF8StringEncoding];

        [self pusblishData:pubData];
    }
}

- (void)pusblishData:(NSData *)data
{
    if(!_publication)
    {
        // This means that the data was not sent

        if(![GNSPermission isGranted])
        {
            [self configureNearbyFramework];
        }

        __weak __typeof__(self) weakSelf = self;
        GNSMessage *dataForPublish = [GNSMessage messageWithContent:data];
        _publication = [self.messageMgr publicationWithMessage:dataForPublish
                                                   paramsBlock:^(GNSPublicationParams *params) {
                                                       __strong __typeof(weakSelf) strongSelf = weakSelf;

                                                       if(strongSelf)
                                                       {
                                                           params.strategy = [strongSelf getStrategy];
                                                       }
                                                   }];

        // The reason why we have to scan after publishing is to check if there is a faliure of data transmission

        [self startScanning];
    }

}

- (void)startScanning
{
    if(![GNSPermission isGranted])
    {
        [self configureNearbyFramework];
    }

    __weak __typeof__(self) weakSelf = self;
    _subscription = [_messageMgr
                     subscriptionWithMessageFoundHandler:^(GNSMessage *message) {
                         __strong __typeof(weakSelf) strongSelf = weakSelf;

                         // Here 
                         }
                     }
                     messageLostHandler:^(GNSMessage *message) {

                         // should we dealloc the _publication here again?
                         __strong __typeof(weakSelf) strongSelf = weakSelf;

                         if(strongSelf)
                         {
                            // Here we loose the message
                         }
                     }
                     paramsBlock:^(GNSSubscriptionParams *params) {

                         __strong __typeof(weakSelf) strongSelf = weakSelf;

                         if(strongSelf)
                         {
                             params.strategy = [strongSelf getStrategy];
                         }

                     }];
}



/// Stops sharing and scanning.
- (void)stopSharingAndScanning {

    if(_publication)
        _publication = nil;

    if(_subscription)
        _subscription = nil;

    if(_messageMgr)
        _messageMgr = nil;

}

#pragma mark - PERMISSION
/// Toggles the permission state of Nearby.
- (void)changeNearbyPermission {
    [GNSPermission setGranted:![GNSPermission isGranted]];
}

#pragma mark - GETTERS
- (GNSMessageManager *)messageMgr
{
    if(!_messageMgr)
    {
        _messageMgr = [[GNSMessageManager alloc] initWithAPIKey:kMyAPIKey paramsBlock:^(GNSMessageManagerParams *params) {
            params.microphonePermissionErrorHandler = ^(BOOL hasError) {
                NSLog(@"Microphone Permission Error:%@", hasError ? @"YES" : @"NO");

            };
            params.bluetoothPowerErrorHandler = ^(BOOL hasError) {
                NSLog(@"Bluetooth Power Error:%@", hasError ? @"YES" : @"NO");

            };
            params.bluetoothPermissionErrorHandler = ^(BOOL hasError) {
                NSLog(@"Bluetooth Permission Error:%@", hasError ? @"YES" : @"NO");
            };
        }];
    }
    return _messageMgr;
}
- (GNSStrategy *)getStrategy
{
    return [GNSStrategy strategyWithParamsBlock:^(GNSStrategyParams *params) {
        params.allowInBackground = NO;
        params.discoveryMediums = kGNSDiscoveryMediumsBLE;
        params.discoveryMode = (_shouldScanForPeers) ? kGNSDiscoveryModeScan : kGNSDiscoveryModeDefault;
    }];
}

I'm creating an object of this Nearby handler class in a View Controller and then passing it to another View Controller where this object would either scan or broadcast, i.e the startScanning/startPublishingDefaultData method is called in viewDidAppear method of the passed View Controller. But my nearby permission dialog never appears, as a result of which the scanning/ publishing doesn't happen. Can you show me where the problem exists in code?

P.S: I thought that my key was invalid but when I applied the same key in the demo project for nearby (https://github.com/googlesamples/ios-nearby), it works properly.

1 Answers1

0

The policy in Nearby Messages is to ask for permission only when iOS requires permission for something (such as for microphone or background BLE). In your case, you're only using BLE in the foreground, and there are no iOS permissions needed for this mode, so Nearby doesn't ask for permission.

Dan Webb
  • 348
  • 1
  • 7
  • Because my permission handler was not responding, neither the subscription nor the publication was working. Do you recommend that I hard code the GNSPermission as YES? – Debanjan Chakraborty May 16 '17 at 06:14
  • Thanks. I just hard coded it and now it's working nicely. – Debanjan Chakraborty May 16 '17 at 10:37
  • I'm glad you got it working, but I'm puzzled about needing to hardwire GNSPermission to YES. I patched your code into the Nearby sample project, and it worked without setting it to YES. In fact, I set it to NO, and it still worked. But, hardwiring it as you've done won't cause any problems. A few coding suggestions: - No need to create a GNSPermission object unless you want to monitor the permission state. - No need to start publishing before scanning. Order doesn't matter. - Change getStrategy to a C function, and you can remove many uses of weak/strong self. – Dan Webb May 17 '17 at 18:07