3

how can I detect a locked/unlocked iOS device using Swift ( like the SCRENON / SCREENOFF in Android )

the_one
  • 261
  • 3
  • 10
  • If you are looking for a swift solution without any Objective-C / Bridging header: http://stackoverflow.com/a/42509825/4177109 – tbaranes Feb 28 '17 at 13:21

1 Answers1

5

I create same think using following.

You need to use the bridge for objective c code use into swift.

Here is the Link for create the bridge between the Objective c to Swift.

Once Completed then you can add following .h file into yourproject-Bridging-Header. file add the yourcontroller.h

Then add NotificationCenter.framework into your project.

Into your CustomObject.m

#import "notify.h"

-(void)registerAppforDetectLockState {

    int notify_token;
    notify_register_dispatch("com.apple.springboard.lockstate", &notify_token,dispatch_get_main_queue(), ^(int token) {

        uint64_t state = UINT64_MAX;
        notify_get_state(token, &state);

        if(state == 0) {
            NSLog(@"unlock device");
        } else {
            NSLog(@"lock device");
        }

        NSLog(@"com.apple.springboard.lockstate = %llu", state);
        UILocalNotification *notification = [[UILocalNotification alloc]init];
        notification.repeatInterval = NSCalendarUnitDay;
        [notification setAlertBody:@"Hello world!! I come becoz you lock/unlock your device :)"];
        notification.alertAction = @"View";
        notification.alertAction = @"Yes";
        [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
        notification.soundName = UILocalNotificationDefaultSoundName;
        [notification setTimeZone:[NSTimeZone  defaultTimeZone]];

        [[UIApplication sharedApplication] presentLocalNotificationNow:notification];

    });
}

Then CustomObject.h

-(void)registerAppforDetectLockState;

Now into swift code you can directly use this method.

var instanceOfCustomObject: LockViewController = LockViewController()
instanceOfCustomObject.registerAppforDetectLockState();

May this helps lot.

Community
  • 1
  • 1
Nimit Parekh
  • 16,776
  • 8
  • 50
  • 72
  • thanks @Nimit Parekh , I was able to make the logs work , The new question is how can we do something when we detect a log using swift code ? :) – the_one Jul 16 '15 at 15:21
  • Usage of this private string is now causing rejections, need to think of an alternative. – Rhythmic Fistman Apr 21 '17 at 04:06
  • @RhythmicFistman now do you having any alternate way please mentation here because above answer now not able to work longer. – Nimit Parekh Apr 21 '17 at 04:08
  • You could replace with detecting going to the background. `UIApplicationDidEnterBackgroundNotification` background and screenlock are slightly correlated – Rhythmic Fistman Apr 21 '17 at 04:10