我最近再次选择了Swift并且我正在开发一个应用程序,它需要我在一个间隔内获取用户坐标以获得最准确的拉动。我的应用程序有权始终跟踪用户位置。我的问题是弄清楚我是如何准确地触发坐标更新,以及接受我在后台运行的应用程序。
我已经在后台函数下的AppDelegate文件中进行了探索,但我能够通过This Script执行更新位置,虽然它导致非常快速的拉动并且计时器调整似乎不起作用。它保持了能量影响:高所以我想找到无影响的逻辑。希望有人能够提供帮助。
请参阅下面的.Swift来源。
//
// ViewController.swift
//
//
// Created by Truman on 10/20/17.
// Copyright © 2017 . All rights reserved.
//
import UIKit
import Foundation
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet var date: UILabel!
@IBOutlet var lastLocation: UILabel!
@IBOutlet var currentLocation: UILabel!
@IBOutlet var imageConnectionStatus: UIImageView!
@IBOutlet var lastLocationMap: MKMapView!
//Get Current Date - Tru
private let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
return formatter
}()
//Location Declaration
let locationManager = CLLocationManager()
let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius, regionRadius)
lastLocationMap.setRegion(coordinateRegion, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Start View Did Load
//Setup location manager
// If location services is enabled get the users location
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.activityType = .otherNavigation
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
//locationManager.startUpdatingLocation()
// Print out the location to the console
}
self.date.text = UserDefaults.standard.string(forKey: "savedDate")
self.lastLocation.text = UserDefaults.standard.string(forKey: "savedLocation")
var setLocation : String
var dataLastLocation : String
//Save device location.
//saveLocation()
let initialLocation = CLLocation(latitude: 33.4641856959831, longitude: -111.919245965591)
centerMapOnLocation(location: initialLocation )
//End View Did Load
}
var activelocation : String = ""
//Did update locations Method
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
let location = locations[locations.count - 1]
let currentLongitude = location.coordinate.longitude
let currentLatitude = location.coordinate.latitude
if location.horizontalAccuracy > 0 {
locationManager.stopUpdatingLocation()
currentLocation.text = "\(location.coordinate.latitude),\(location.coordinate.longitude)"
//print("longitude = \(location.coordinate.longitude), latitude = \(location.coordinate.latitude)")
// Need to use Current User Location vs Last Seen location in Maps URLS Below
activelocation = "http://maps.google.com/?saddr=\(UserDefaults.standard.string(forKey: "savedLocation")!)&daddr=\(currentLatitude),\(currentLongitude)"
self.locationManager.allowsBackgroundLocationUpdates = true
}
}
//Setting Saved data values--
func setPersistent(){
let defaults = UserDefaults.standard
let when = DispatchTime.now() + 5 // change 2 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: when) {
let oldDate = self.date.text
defaults.set(oldDate, forKey: "savedDate")
self.date.text = oldDate
print(UserDefaults.standard.string(forKey: "savedDate"))
//locationManager.startUpdatingLocation()
let oldLocation = self.currentLocation.text
defaults.set(oldLocation, forKey: "savedLocation")
self.lastLocation.text = "Saved Location:\(oldLocation)"
// print("this is the old location:\(oldLocation)")
print(UserDefaults.standard.string(forKey: "savedLocation"))
let saveDate = UserDefaults.standard.object(forKey: "saveLast")
let saveLastLocation = UserDefaults.standard.object(forKey: "saveLastLocation")
}
}
func saveLocation(){
// print("longitude = \(location.coordinate.longitude), latitude = \(location.coordinate.latitude)")
}
//Did Fail Update
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error){
print(Error.self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Get Current Date and time.
func getTodayString() -> String{
let date = Date()
let calender = Calendar.current
let components = calender.dateComponents([.year,.month,.day,.hour,.minute,], from: date)
let today_string = String(month)
return today_string
}
let today : String
today = getTodayString()
UserDefaults.standard.set("\(today)", forKey: "saveLast")
//self.lastLocation.text = "hello"
self.locationManager.startUpdatingLocation()
self.setPersistent()
} else if state == false {
let when = DispatchTime.now() + 2 // change 2 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: when) {
}
}
// locationManager.startUpdatingLocation()
let now = NSDate()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM d, y hh:mm:ss"
let month = dateFormatter.string(from: now as Date)
//self.date.text = dateFormatter.string(from: now as Date)
//Get Current Date andd time.
func getTodayString() -> String{
let date = Date()
let calender = Calendar.current
let components = calender.dateComponents([.year,.month,.day,.hour,.minute,], from: date)
let today_string = String(month)
return today_string
}
let today : String
today = getTodayString()
UserDefaults.standard.set("\(today)", forKey: "saveLast")
}
}