一个简单的速度计类,适用于iOS和WatchOS。
使用 iPhone 或 Apple Watch 测量速度。
注意
演示 UI 是使用 LidorFadida 的软件包 SpeedometerSwiftUI 创建的。
我喜欢在火车和公共汽车上测量我的速度。 当我搜索速度计应用程序时,大多数都很丑陋,并且包含大量广告。 我一直在寻找带有复杂功能的 Apple Watch 速度计和带有 Widget 的 iOS App,但没有找到。 因此,我决定创建自己的应用程序。 第一件事是使用 CLLocationManager
测量速度。
Swift Package Manager 是安装和管理 SpeedManagerModule 作为依赖项的最简单方法。 只需将 SpeedManagerModule 添加到您的 Package.swift 文件中的依赖项中即可。
dependencies: [
.package(url: "https://github.com/ezefranca/SpeedManagerModule.git")
]
添加正确的权限描述
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Your description why you should use NSLocationAlwaysAndWhenInUseUsageDescription</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Your description why you should use NSLocationAlwaysAndWhenInUseUsageDescription</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Your description why you should use NSLocationAlwaysAndWhenInUseUsageDescription</string>
在 Xcode 中添加后台位置更新
或者将信息添加到 Info.plist
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
import SwiftUI
struct ContentView: View {
@StateObject var speedManager = SpeedManager(.kilometersPerHour)
var body: some View {
VStack {
switch speedManager.authorizationStatus {
case .authorized:
Text("Your current speed is:")
Text("\(speedManager.speed)")
default:
Spacer()
}
}
}
}
import UIKit
class SpeedViewController: UIViewController {
var speedManager = SpeedManager(.kilometersPerHour)
override func viewDidLoad() {
super.viewDidLoad()
self.speedManager.delegate = self
self.speedManager.startUpdatingSpeed()
}
}
extension SpeedViewController: SpeedManagerDelegate {
func speedManager(_ manager: SpeedManager, didUpdateSpeed speed: Double, speedAccuracy: Double) {
// Update UI with the current speed and accuracy
}
func speedManager(_ manager: SpeedManager, didFailWithError error: Error) {
// Handle error
}
func speedManager(_ speedManager: SpeedManager, didUpdateAuthorizationStatus status: SpeedManagerAuthorizationStatus) {
// Handle authorization status update
}
func speedManagerDidFailWithLocationServicesUnavailable(_ speedManager: SpeedManager) {
// Handle location services unavailable
}
}
只需在类初始化期间选择单位。
var speedManagerKmh = SpeedManager(.kilometersPerHour)
var speedManagerMs = SpeedManager(.metersPerSecond)
var speedManagerMph = SpeedManager(.milesPerHour)
查看Demo
文件夹以查看实际效果。
@ezefranca – @ezefranca
根据 MIT 许可证分发。 有关更多信息,请参见 LICENSE
。