应用程序在后台Swift 2中从应用程序获取数据

时间:2016-10-18 18:39:00

标签: ios swift background locationmanager

我试图想办法让他/她的用户在一英里的路程中得到通知,我的代码如下:

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)
}

现在我对我的编码进行了解释:我添加了一个计时器(counter),因为我还想为我的应用程序的用户计时。我注意到当我的应用程序在后台时func updateCounter()仍在运行,所以我想我是否设置了我的代码以检查roundDistance是否已达到该功能的一英里,我的应用程序将发送通知。没运气!我得出的结论是,我的应用程序可能在后台更新用户的位置,这就是为什么我的计时器在后台更新但roundDistance不是&{ #39;吨。有人可以帮助我找到一个解决方案,我可以在我的应用程序在后台时获得位置和roundDistance实时更新吗?

0 个答案:

没有答案