Thursday 22 October 2015

Proximity in IOS application


First of all what is proximity in IOS ?

Do you ever play audio in Whatsapp in iphone ? when it is playing far from the face its volume is high and when you take it near to your ear or face then you can hear the audio in Receiver from microphone. This functionality is implemented by checking proximity.

First  Proximity can not be checked in Ipod and Ipad , You can check whether your device support Proximity or not by implement this code.

      
UIDevice *device = [UIDevice currentDevice];
device.proximityMonitoringEnabled = YES;    

if (device.proximityMonitoringEnabled == YES) // yes your device support proximity
{
    NSLog(@"proximity enabled");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityChanged:) name:@"UIDeviceProximityStateDidChangeNotification" object:device];
} else {
    NSLog(@"proximity not enabled");
}


When proximity change you can change your avaudiosession property When your device is near to your face you can overrideOutputAudioPort to    AVAudioSessionPortOverrideNone and when your
device is far from your face you can overrideOutputAudioPort to    AVAudioSessionPortOverrideSpeaker so it will play in speaker

- (void) proximityChanged:(NSNotification *)notification {
    NSLog(@"proximity changed called");
    UIDevice *device = [notification object];
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    BOOL success;
     success = [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    if(device.proximityState == 1){
        NSLog(@"bool %s", success ? "true" : "false");
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
        [audioSession setActive:YES error:nil];
    }
    else{
        NSLog(@"bool %s", success ? "true" : "false");
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
        [audioSession setActive:YES error:nil];
        }
}


Now proximity should be off when it is not needed , that's why in viewWillAppear of each screen you should make it of and only when your audio is playing on it .

 -(void)viewWillAppear:(BOOL)animated
    {   
        [super viewWillAppear:animated];

        UIDevice *device = [UIDevice currentDevice];

        device.proximityMonitoringEnabled = NO;
    }

1 comment:

  1. Sukaan Ota - Hotel - South Korea - Kirill Kondrashin
    Sukaan Ota is owned and operated by the Hotel and Casino of South Korea in the heart of Easton. 카지노 The hotel is located kirill-kondrashin on the border.

    ReplyDelete