I'm trying to figure out a way to have my app's user notified when he/she travels a mile, my code is as following:
var roundDistance:Double!
var startTime = NSTimeInterval()
var timeCounter = NSTimer()
var counter = 0
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if startLocation == nil {
startLocation = locations.first
} else {
if let lastLocation = locations.last {
let distance = startLocation.distanceFromLocation(lastLocation)
let lastDistance = lastLocation.distanceFromLocation(lastLocation)
let startPoint = startLocation.coordinate
let lastPoint = lastLocation.coordinate
let blah = locations.last!.coordinate
var area = [blah,lastPoint]
var polyLine = MKPolyline(coordinates: &area, count: area.count)
mapOfMaps.addOverlay(polyLine)
traveledDistance += lastDistance
SpeedLevel.text = "\(lastLocation.speed) mph"
roundDistance = round(100*(distance/1609.344))/100 //converting my distance to miles
distanceLabel.text = "\(roundDistance!) miles"
}
}
lastLocation = locations.last
let center = CLLocationCoordinate2D(latitude: lastLocation.coordinate.latitude, longitude: lastLocation.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)) //zoom in on user's location on map
self.mapOfMaps.setRegion(region, animated: true)
}
func updateCounter(){
counter += 1
print(counter)
print("STRAIGHT DISTANCE: \(roundDistance!)")
if (roundDistance == 1.0){
let notification = UILocalNotification()
notification.alertBody = "you've ran \(String(roundDistance!)) miles!"
//notification.alertAction = "open"
notification.fireDate = NSDate(timeIntervalSinceNow:1)
notification.soundName = UILocalNotificationDefaultSoundName // play default sound
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
}
@IBAction func StartItUp(sender: UIButton) { //start timer and starts location services
startTime = NSDate.timeIntervalSinceReferenceDate()
timeCounter = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(CardioViewController.updateCounter), userInfo: nil, repeats: true)
}
now for my explanation on my coding: I added a timer (counter
) because I also want to time my app's user. I've noticed that func updateCounter()
is still being run when my app is in the background so I figured if I set my code to check if roundDistance
has reached a mile in the function, my app would send a notification. No luck! I've come to conclusion that perhaps my app isn't updating the user's location while it is in the background, which is why my timer is being updated in the background but roundDistance
isn't. Can someone please help me with a solution where I can have the location and roundDistance
updated real time while my app is in the background?