我正在编写一个 iOS 应用程序,用于在参与的零售地点扫描条形码,在客户扫描打印在收据上的二维码后,该地点将代表客户向慈善机构捐款。
如果用户在参与地点停留 60 秒或更长时间,我想向他们发送本地通知,提醒他们扫描他们可能从那里购买的任何收据。
我的问题是,当用户进入某个区域时,我想将呼叫延迟 60 秒 - 如果在 60 秒之后他们仍在该区域中触发本地通知 - 但是,有时在 stillInRegion 中对 sendLocalNotification 的调用不会开火,直到应用程序返回前台。我相信这与线程有时在延迟结束之前结束有关,但我不确定。我已经尝试了在 stackoverflow 和其他地方(块、nstimers 等)上可以找到的所有方法,但无济于事。关于如何更好地解决这个问题的任何想法?
- (void) sendLocalNotification:(NSString *)regionId {
NSLog(@"we entered %@ and we're currently in %@", regionId, self.currentRegionId);
if ([regionId isEqualToString:self.currentRegionId]) {// if we're still in the region, send a local notification
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil) return;
NSDate *fireTime = [[NSDate date] addTimeInterval:2]; // adds 2 secs
localNotif.fireDate = fireTime;
localNotif.alertBody = [NSString stringWithFormat:@"Did you just visit %@? If so, don't forget to scan your receipt!", regionId];
localNotif.applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber+1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
}
}
- (void) stillInRegion:(CLRegion *)region {
NSLog(@"did enter region: %@", region.identifier);
[self performSelector:@selector(sendLocalNotification:) withObject:region.identifier afterDelay:60];
}
- (void) locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
if (self.didLaunchForRegionUpdate) {
NSString *path = [DGGeofencingHelper applicationDocumentsDirectory];
NSString *finalPath = [path stringByAppendingPathComponent:@"notifications.dg"];
NSMutableArray *updates = [NSMutableArray arrayWithContentsOfFile:finalPath];
if (!updates) {
updates = [NSMutableArray array];
}
NSMutableDictionary *update = [NSMutableDictionary dictionary];
[update setObject:region.identifier forKey:@"fid"];
[update setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"timestamp"];
[update setObject:@"enter" forKey:@"status"];
[updates addObject:update];
[updates writeToFile:finalPath atomically:YES];
} else {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"enter" forKey:@"status"];
[dict setObject:region.identifier forKey:@"fid"];
NSString *jsStatement = [NSString stringWithFormat:@"DGGeofencing.regionMonitorUpdate(%@);", [dict JSONString]];
[self.webView stringByEvaluatingJavaScriptFromString:jsStatement];
}
self.currentRegionId = region.identifier;
self.cRegionEnterTime =[NSDate date];
[self stillInRegion:region];
}