退出信标时获取通知

Posted

技术标签:

【中文标题】退出信标时获取通知【英文标题】:Get notification when exiting from the beacons 【发布时间】:2016-03-03 06:01:44 【问题描述】:

我正在与三个 iBeacons 合作,以在 iPhone/iPad 上查找其范围以进行考勤程序。我需要应用程序可以识别三个信标,并且当用户进入任何一个信标的区域时,他们应该收到他们已登录的通知。并且它应该只在用户退出所有三个信标时注销。

同时,如果用户已经登录或进入新的信标,用户不应收到任何通知。(意味着用户将他的位置从一个信标更改为另一个信标的区域)。

在我的代码中,三个信标被识别并获得登录通知。但是退出三个信标时它不会被注销,而在该区域内时它不会被注销并更改为一个信标到另一个信标。

请任何人帮助我解决我的问题。

这是我的代码:

NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
    [parameters setObject:EmpID.text forKey:@"eid"];
    [parameters setObject:@"entry" forKey:@"type"];

    NSLog(@"Params:%@",parameters);

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AFHTTPRequestOperationManager *sermanager = [AFHTTPRequestOperationManager manager];
    sermanager.responseSerializer = [AFHTTPResponseSerializer serializer];
    sermanager.requestSerializer = [AFJSONRequestSerializer serializer];
    [sermanager.requestSerializer setValue:@"parse-application-id-removed" forHTTPHeaderField:@"X-Parse-Application-Id"];
    [sermanager.requestSerializer setValue:@"parse-rest-api-key-removed" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
    [sermanager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    sermanager.securityPolicy.allowInvalidCertificates = YES;


    NSString *urlString=[NSString stringWithFormat:@"http://livmob.com/beacon/index.php/api/Employee/getEmployeeDetails"];

    [sermanager POST:urlString parameters:parameters  success:^(AFHTTPRequestOperation *operation, id responseObject)
     
         NSError *error = nil;
         NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
         NSLog(@"JSON:%@",JSON);

         [MBProgressHUD hideHUDForView:self.view animated:YES];
         NSString *empIdGet=[JSON valueForKeyPath:@"Response.employeeDetail.eid"][0];
         NSArray *bloodGroup=[JSON valueForKeyPath:@"Response.employeeDetail.bloodGroup"][0];
         NSArray *department=[JSON valueForKeyPath:@"Response.employeeDetail.department"][0];
         NSArray *dob=[JSON valueForKeyPath:@"Response.employeeDetail.dob"][0];
         NSArray *email=[JSON valueForKeyPath:@"Response.employeeDetail.email"][0];
         NSArray *name=[JSON valueForKeyPath:@"Response.employeeDetail.name"][0];
         NSArray *phone=[JSON valueForKeyPath:@"Response.employeeDetail.phone"][0];
         NSArray *photo=[JSON valueForKeyPath:@"Response.employeeDetail.photo"][0];
         NSArray *role=[JSON valueForKeyPath:@"Response.employeeDetail.role"][0];

         empid=empIdGet;

         [[NSUserDefaults standardUserDefaults]setObject:empIdGet forKey:@"EMPID"];
         [[NSUserDefaults standardUserDefaults]setObject:role forKey:@"EMP_ROLE"];
         [[NSUserDefaults standardUserDefaults]setObject:photo forKey:@"EMP_PHOTO"];
         [[NSUserDefaults standardUserDefaults]setObject:phone forKey:@"EMP_PHONE"];
         [[NSUserDefaults standardUserDefaults]setObject:name forKey:@"EMP_NAME"];
         [[NSUserDefaults standardUserDefaults]setObject:email forKey:@"EMP_EMAIL"];
         [[NSUserDefaults standardUserDefaults]setObject:dob forKey:@"EMP_DOB"];
         [[NSUserDefaults standardUserDefaults]setObject:department forKey:@"EMP_DEPT"];
         [[NSUserDefaults standardUserDefaults]setObject:bloodGroup forKey:@"EMP_BLOOD"];


         NSUUID * nearUUID =[[NSUUID alloc] initWithUUIDString:[NSString stringWithFormat:@"B9407F30-F5F8-466E-AFF9-25556B57FE6D"]];

         self.beaconRegion =[[CLBeaconRegion alloc]initWithProximityUUID:nearUUID identifier:@"near"];
         [self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
         [self.locationManager startMonitoringForRegion:self.beaconRegion];
         UUIDStr = [nearUUID UUIDString];

         NSUUID *nearUUID1 =[[NSUUID alloc] initWithUUIDString:[NSString stringWithFormat:@"6CA02DDF-78A2-3F7E-DD54-238F91B19E57"]];

         self.beaconRegion1 =[[CLBeaconRegion alloc]initWithProximityUUID:nearUUID1 identifier:@"near"];

         [self.locationManager startRangingBeaconsInRegion:self.beaconRegion1];
         [self.locationManager startMonitoringForRegion:self.beaconRegion1];
         UUIDStr1 = [nearUUID1 UUIDString];

NSUUID *nearUUID2 =[[NSUUID alloc] initWithUUIDString:[NSString stringWithFormat:@"DD5D08FD-303F-4B8B-D8FB-89D491955B2E"]];

         self.beaconRegion1 =[[CLBeaconRegion alloc]initWithProximityUUID:nearUUID2 identifier:@"near"];

         [self.locationManager startRangingBeaconsInRegion:self.beaconRegion1];
         [self.locationManager startMonitoringForRegion:self.beaconRegion1];
         UUIDStr2 = [nearUUID2 UUIDString]; 

         [self entryMethod];

         self.proximityContentManager = [[ProximityContentManager alloc]
                                         initWithBeaconIDs:@[
                                                             [[BeaconID alloc] initWithUUIDString:@"6CA02DDF-78A2-3F7E-DD54-238F91B19E57" major:41073 minor:64330],
                                                             [[BeaconID alloc] initWithUUIDString:@"B9407F30-F5F8-466E-AFF9-25556B57FE6D" major:590 minor:16462],
                                                             [[BeaconID alloc] initWithUUIDString:@"DD5D08FD-303F-4B8B-D8FB-89D491955B2E" major:41749 minor:53281]
                                                             ]
                                         beaconContentFactory:[[CachingContentFactory alloc] initWithBeaconContentFactory:[BeaconDetailsCloudFactory new]]];
         self.proximityContentManager.delegate = self;

         [self.proximityContentManager startContentUpdates];

     
             failure:^(AFHTTPRequestOperation *operation, NSError *error)
     

         [MBProgressHUD hideHUDForView:self.view animated:YES];

         NSLog(@"Error:%@",error.localizedDescription);
     ];

    
return YES;


- (void)proximityContentManager:(ProximityContentManager *)proximityContentManager didUpdateContent:(id)content


BeaconDetails *beaconDetails = content;
if (beaconDetails)

    NSLog(@"beaconDetails %@",beaconDetails.beaconName);
    beaconNameStr = beaconDetails.beaconName;



- (UIStatusBarStyle)preferredStatusBarStyle 
return UIStatusBarStyleLightContent;



- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region





- (void)locationManager:(CLLocationManager *)manager
    didRangeBeacons:(NSArray *)beacons
           inRegion:(CLRegion *)region


NSLog(@"Own Beacons %@",beacons);

self.beaconsArray = beacons;


for (CLBeacon *beacon in self.beaconsArray)

    if (beacon.proximity == CLProximityImmediate)
    
        NSLog(@"Own State Immediate %@",beaconNameStr);
    
    else if (beacon.proximity == CLProximityNear)
    
        NSLog(@"Own State Near %@",beaconNameStr);
    
    else if (beacon.proximity == CLProximityFar)
    
        NSLog(@"Own State Far %@",beaconNameStr);
    
    else if (beacon.proximity == CLProximityUnknown)
    
        NSLog(@"Own State Unknown %@",beaconNameStr);
    
    else
    
        NSLog(@"Own Exited %@",beaconNameStr);


    




-(void)entryMethod


NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"Already entered" forKey:@"userstatus"];

NSString *statusStr =[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"userstatus"]];

if ([statusStr isEqualToString:@"Already entered"])


[defaults synchronize];
NSString *empIdNew =[defaults objectForKey:@"EMPID"];

NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
[parameters setObject:empIdNew forKey:@"eid"];
[parameters setObject:@"entry" forKey:@"type"];

NSLog(@"Params:%@",parameters);


AFHTTPRequestOperationManager *sermanager = [AFHTTPRequestOperationManager manager];
sermanager.responseSerializer = [AFHTTPResponseSerializer serializer];
sermanager.requestSerializer = [AFJSONRequestSerializer serializer];
[sermanager.requestSerializer setValue:@"parse-application-id-removed" forHTTPHeaderField:@"X-Parse-Application-Id"];
[sermanager.requestSerializer setValue:@"parse-rest-api-key-removed" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
[sermanager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
sermanager.securityPolicy.allowInvalidCertificates = YES;

NSString *urlString=[NSString stringWithFormat:@"http://livmob.com/beacon/index.php/api/Employee/employeeLogin"];

[sermanager POST:urlString parameters:parameters  success:^(AFHTTPRequestOperation *operation, id responseObject)
 
     NSError *error = nil;
     NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
     NSLog(@"JSON:%@",JSON);

 


         failure:^(AFHTTPRequestOperation *operation, NSError *error)
 
     NSLog(@"Error");
 ];


NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 synchronize];
[defaults1 setValue:@"You are Time In" forKey:@"defaultStatus"];

SeconVC *second = (SeconVC *)[self.storyboard instantiateViewControllerWithIdentifier:@"SeconVC"];
[self.navigationController pushViewController:second animated:YES];


else 
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate date];
notification.alertBody = @"You are Time In!";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];

//*******************************didEnterRegion:***************************************//

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region

    [self.proximityContentManager startContentUpdates];

    NSLog(@"Emp ID:%@",empid);

    NSString *statusStr =[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"userstatus"]];

    if (![statusStr isEqualToString:@"Already entered"])
    


        [NSObject cancelPreviousPerformRequestsWithTarget:self
                                         selector:@selector(PerformingDelay)
                                           object:nil];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

        [defaults setObject:@"Already entered" forKey:@"userstatus"];
        [defaults synchronize];
        NSString *empIdNew =[defaults objectForKey:@"EMPID"];

            if ([UUIDStr isEqualToString:@"B9407F30-F5F8-466E-AFF9-25556B57FE6D"] || [UUIDStr1 isEqualToString:@"6CA02DDF-78A2-3F7E-DD54-238F91B19E57"])
            
                NSLog(@"you are Login into %@",beaconNameStr);

                NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
                [parameters setObject:empIdNew forKey:@"eid"];
                [parameters setObject:@"entry" forKey:@"type"];

                NSLog(@"Params:%@",parameters);

                if (empid.length ==0)
                
                    NSLog(@"No values are passed");
                
                else
                
                    [[NSUserDefaults standardUserDefaults]setObject:statusStrNew forKey:@"EMPID"];


                    NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
                    [defaults1 synchronize];
                    [defaults1 setValue:@"You are Time In" forKey:@"defaultStatus"];

                    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                    SeconVC *viewController = [storyboard instantiateViewControllerWithIdentifier:@"SeconVC"];

                    UILocalNotification *notification = [[UILocalNotification alloc] init];
                    notification.fireDate = [NSDate date];
                    notification.alertBody = @"You are Time In!";
                    notification.timeZone = [NSTimeZone defaultTimeZone];
                    notification.soundName = UILocalNotificationDefaultSoundName;
                    [[UIApplication sharedApplication] scheduleLocalNotification:notification];

                    if (timeStr.length ==0) 
                        NSLog(@"No values passed");
                    
                    else
                        NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
                        [parameters setObject:timeStr forKey:@"logoutTime"];

                    AFHTTPRequestOperationManager *sermanager = [AFHTTPRequestOperationManager manager];
                    sermanager.responseSerializer = [AFHTTPResponseSerializer serializer];
                    sermanager.requestSerializer = [AFJSONRequestSerializer serializer];
                    [sermanager.requestSerializer setValue:@"parse-application-id-removed" forHTTPHeaderField:@"X-Parse-Application-Id"];
                    [sermanager.requestSerializer setValue:@"parse-rest-api-key-removed" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
                    [sermanager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                    sermanager.securityPolicy.allowInvalidCertificates = YES;

                    NSString *urlString=[NSString stringWithFormat:@"http://livmob.com/beacon/index.php/api/Employee/employeeLogin"];

                    [sermanager POST:urlString parameters:parameters  success:^(AFHTTPRequestOperation *operation, id responseObject)
                     
                         NSError *error = nil;
                         NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
                         NSLog(@"JSON:%@",JSON);

                     
                             failure:^(AFHTTPRequestOperation *operation, NSError *error)
                     
                         NSLog(@"Error");


                     ];
                    
                
            
    
    

//*******************************Exit Functions****************//
-(void)PerformingDelay


        NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
        [defaults1 synchronize];
        [defaults1 setValue:@"You are Time Out" forKey:@"defaultStatus"];

        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.fireDate = [NSDate date];
        notification.alertBody = @"You are Time Out!";
        notification.timeZone = [NSTimeZone defaultTimeZone];
        notification.soundName = UILocalNotificationDefaultSoundName;
        NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"You Left!"
                                                             forKey:@"Notify"];
        notification.userInfo = userDict;
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];


        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults synchronize];
        NSString *empId =[defaults objectForKey:@"EMPID"];
        [defaults setObject:@"User Left" forKey:@"userstatus"];

        if (empId.length ==0)
        
            NSLog(@"No values are passed");
        
        else
        

            @try
            
                NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
                [parameters setObject:empId forKey:@"eid"];
                [parameters setObject:@"exit" forKey:@"type"];

                NSLog(@"Params:%@",parameters);


                NetworkStatus internetStatus = [reachability currentReachabilityStatus];
                if (internetStatus == NotReachable)
                

                    UILocalNotification *notification = [[UILocalNotification alloc] init];

                    notification.fireDate = [NSDate date];

                    notification.alertBody = @"Internet connection is lost, your attendance status will not be updated. Please check your internet connection to update it.";

                    notification.timeZone = [NSTimeZone defaultTimeZone];

                    notification.soundName = UILocalNotificationDefaultSoundName;

                    [[UIApplication sharedApplication] scheduleLocalNotification:notification];

                    timeStr = [NSString stringWithFormat:@"%@",[NSDate date]];
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    [formatter setDateFormat:@"hh:mm:ss"];

                    NSDate *date = [formatter dateFromString:timeStr];

                    [[NSUserDefaults standardUserDefaults] setObject:date forKey:@"logoutTime"];

                
                else
                

                AFHTTPRequestOperationManager *sermanager = [AFHTTPRequestOperationManager manager];
                sermanager.responseSerializer = [AFHTTPResponseSerializer serializer];
                sermanager.requestSerializer = [AFJSONRequestSerializer serializer];
                [sermanager.requestSerializer setValue:@"parse-application-id-removed"  forHTTPHeaderField:@"X-Parse-Application-Id"];
                [sermanager.requestSerializer setValue:@"parse-rest-api-key-removed" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
                [sermanager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                sermanager.securityPolicy.allowInvalidCertificates = YES;

                NSString *urlString=[NSString stringWithFormat:@"http://livmob.com/beacon/index.php/api/Employee/employeeLogin"];

                [sermanager POST:urlString parameters:parameters  success:^(AFHTTPRequestOperation *operation, id responseObject)
                 
                     NSError *error = nil;
                     NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
                     NSLog(@"JSON:%@",JSON);

                 
                         failure:^(AFHTTPRequestOperation *operation, NSError *error)
                 
                     NSLog(@"Error");
                 ];
                            
            
            @catch (NSException *exception)
            
                NSLog(@"Emp Id Error");
            
        
    



- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region


[MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [self performSelector:@selector(PerformingDelay) withObject:nil afterDelay:120.0];
    NSLog(@"User Logged Out %@", beaconNameStr);

    NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
    [defaults1 synchronize];
    [defaults1 setValue:@"You are Time Out" forKey:@"defaultStatus"];

提前致谢!

【问题讨论】:

那是 423 行代码。如果你减少它,你将大大增加获得帮助的机会,更多地关注“最小,完整和可验证的示例”中的“最小”(***.com/help/mcve) 【参考方案1】:

您的代码太多,我无法阅读。我并没有真正经历过。

您有 3 个用于 3 个信标(区域)的 UUID。 每次进入/退出,ios 都会有一个回调 didEnterRegion 和 didExitRegion 独立。

您需要做的是使用一个变量来记录 3 个区域的状态,进出。 然后检查每个 didEnterRegion/didExitRegion 回调中的状态,并具有如下规则:

didEnterRegion:

if 0 in 变为 1 in : 用户先进入区域

didExitRegion

如果 x in 变为 0 in (x != 0):用户首先完全退出该区域

希望对您有所帮助。

【讨论】:

对不起,因为我是新手(发布问题),以后会在这里。无论如何感谢您的回答。它对我有用。很抱歉回复晚了。

以上是关于退出信标时获取通知的主要内容,如果未能解决你的问题,请参考以下文章

如何在 didExitRegion 中获取信标主要和次要 id

如何在 iOS 后台模式下获取信标广告数据

Swift iBeacon 只有一个信标被监控

在iOS中测距和监控时如何获取信标的MAC地址

设置范围区域 iBeacons

在后台监控期间接收来自信标区域检测的通知