2017-08-24 47 views
1

我試圖顯示用戶的平均速度, ,我也想顯示數組的最高值。陣列「CoreLocation」的平均速度和最高速度

我搜索了論壇,發現了很多方法來完成這個,但沒有任何工作。

我曾嘗試在// top speed// average speed

這裏是我的代碼:

// Location 
let manager = CLLocationManager() 

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    let location = locations[0] 
    let span = MKCoordinateSpanMake(0.015, 0.015) 
    let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude) 

    let region = MKCoordinateRegionMake(myLocation, span) 
    mapView.setRegion(region, animated: true) 
    self.mapView.showsUserLocation = true 

    // Altitude 
    let altitude = location.altitude 
    let altitudeNoDecimals = Int(altitude) 

    altitudeLabel.text = "\(altitudeNoDecimals)" 

    // m/s to km/h 
    let kmt = location.speed * (18/5) 
    let kmtLabel = Int(kmt) 
    statusLabel.text = "\(kmtLabel)" 

    // Top Speed 
    // let maxSpeed: Int = (kmtLabel as AnyObject).value(forKeyPath: "@maxSpeed.self") as! Int 
    // topSpeedLabel.text = "\(maxSpeed)" 

    let max = location.toIntMax() 
    topSpeedLabel.text = "\(max)" 

    // Average speed 
    var avg: Double = (list as AnyObject).valueForKeyPath("@avg.self") as Double 
    averageSpeed.text = "\(avg)" 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    manager.delegate = self 
    manager.desiredAccuracy = kCLLocationAccuracyBest 
    manager.requestWhenInUseAuthorization() 
    manager.startUpdatingLocation() 
} 

回答

0

你一定要所有的速度更新保存到一個數組自己,這應該被定義爲一類實例屬性,您可以將平均速度和最高速度都定義爲計算屬性,因此您無需在每次接收位置更新時手動更新它們。

let manager = CLLocationManager() 
var speeds = [CLLocationSpeed]() 
var avgSpeed: CLLocationSpeed { 
    return speeds.reduce(0,+)/Double(speeds.count) //the reduce returns the sum of the array, then dividing it by the count gives its average 
} 
var topSpeed: CLLocationSpeed { 
    return speeds.max() ?? 0 //return 0 if the array is empty 
} 

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    let location = locations[0] 
    ... 

    speeds.append(contentsOf: locations.map{$0.speed}) //append all new speed updates to the array 

    // m/s to km/h 
    let kmt = location.speed * (18/5) 
    let kmtLabel = Int(kmt) 
    statusLabel.text = "\(kmtLabel)" 

    // Top Speed 
    topSpeedLabel.text = "\(topSpeed)" 

    // Average speed 
    averageSpeed.text = "\(avgSpeed)" 
} 
記住

熊,我沒有任何avgSpeedtopSpeed單位更改爲公里/小時,如果你需要,你可以做到這一點它們寫入標籤之前或者說它們附加到前陣列。

+0

爲什麼選擇投票,請評論。 –

+1

感謝您在我的代碼和解釋性評論中努力實現您的答案。它像一個魅力一樣工作! –

+0

很高興我能幫到你。 –