XCode 11: фоновый мониторинг области не работает - PullRequest
0 голосов
/ 17 июня 2020

После нескольких часов чтения и перекодирования я все еще не могу найти решение.

Я хочу создать простое приложение, которое отслеживает мое местоположение в фоновом режиме. При первой загрузке приложения я настраиваю область вокруг моего текущего местоположения, запускаю мониторинг именно для этого региона и останавливаю обновлениеLocations. Как только приложение получает событие didExitRegion, я снова получаю текущее местоположение, настраиваю другой регион (после очистки всех других отслеживаемых регионов), и все начинается заново.

Приложение всегда имеет авторизацию для местоположения, фоновый режим для местоположения обновления установлены, PList содержит LocationAlwaysAndWhenInUseUsageDescription и LocationWhenInUseUsageDescription.

Некоторое время он отлично работает. Но после многих часов бездействия приложение приостанавливается и больше не получает обновлений о местоположении, даже о событии монитора, которое должно перезапустить приложение, когда я правильно понимаю this ().

* 1008 подсказка?

Спасибо.

import UIKit
import CoreLocation
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

let locationManager = CLLocationManager()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {


    let currentNotifications = UNUserNotificationCenter.current()


    currentNotifications.getNotificationSettings { (settings) in
        if settings.authorizationStatus == .notDetermined {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { (granted, error) in }
        }
    }


    locationManager.delegate = self
    locationManager.requestAlwaysAuthorization()
    locationManager.allowsBackgroundLocationUpdates = true
    locationManager.startUpdatingLocation()


    return true
}

}

extension AppDelegate: CLLocationManagerDelegate {


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {


    let location = locations[0]


    let now = Date()
    let formatter = DateFormatter()


    formatter.timeZone = TimeZone.current
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"


    for region in locationManager.monitoredRegions {
        locationManager.stopMonitoring(for: region)
    }


    var regionIdentifier = String(format: "%f", location.coordinate.latitude) + ", " + String(format: "%f", location.coordinate.latitude) + "( set on " + formatter.string(from: now) + ")"


    var geofenceRegion = CLCircularRegion(center: CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude), radius: 250, identifier: regionIdentifier)


    geofenceRegion.notifyOnExit = true
    locationManager.startMonitoring(for: geofenceRegion)


    locationManager.stopUpdatingLocation()


}




func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
    locationManager.stopMonitoring(for: region)
    sendNotification(title: "Event triggered", subtitle: "Region exit", body: region.identifier)
    locationManager.startUpdatingLocation()
}


}

public func sendNotification(title: String, subtitle: String, body: String) {


let content = UNMutableNotificationContent()
content.title = title
content.subtitle = subtitle
content.body = body
content.sound = .default


let identifier = "geoStalker4_notification_" + String(format: "%f", NSDate().timeIntervalSince1970)


let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)


let request = UNNotificationRequest(identifier: identifier, content: content, trigger: nil)


UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)


}
...