I have been working on an iBeacon app and i'm trying to make it so it posts to a slack room when the user has exited the region for more than 15 minutes. I have tried to start a timer, I've tried to use a start time and then an end time(that was working but I had no way of stopping the loop if the user returned to a beacon). I have all the slack api code, I just need help with code that counts how long someone has been out of the beacon region and if its more than 15 minutes, do some code. Here is the code.. it goes through the loop, but if the user enters back in to a region it does not pick it up.
func locationManager(manager: CLLocationManager!,
didExitRegion region: CLRegion!) {
outOfRegion = true
let start = NSDate(); // <<<<<<<<<< Start time
let viewController:ViewController = window!.rootViewController as! ViewController
var names = viewController.theName
NSLog("You exited the region")
sendLocalNotificationWithMessage("You exited the region", playSound: true)
println(locationManager)
while (outOfRegion) {
println(outOfRegion)
let end = NSDate(); // <<<<<<<<<< end time
let timeInterval: Double = end.timeIntervalSinceDate(start); // <<<<< Difference in seconds (double)
println("Time to evaluate problem: \(timeInterval) seconds");
manager.startMonitoringForRegion(region as! CLBeaconRegion)
manager.startUpdatingLocation()
if (timeInterval > 60) {
//posting to slack API
var channel = "#botspam"
let username = "spyBot"
let text = names + " has left the office"
let image = ":eyes:"
//payload array
let str = "payload={\"channel\": \"\(channel)\", \"username\": \"\(username)\", \"text\": \"\(text)\", \"icon_emoji\": \"\(image)\"}"
// converting to JSON
let strData = (str as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
//Fusionary web hook
let url = NSURL(string: "///////")
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
request.HTTPBody = strData
//checking to see if array is valid JSON
var error : NSError? = nil
if let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: &error) {
let results = NSString(data:data, encoding:NSUTF8StringEncoding)
println(results)
}
else
{
println("data invalid")
println(error)
}
break;
}
println("bye")
}
}