在我的指南针应用程序中,我显示了航向,但性能不高:当我快速转动设备时,不会显示所有度数。我搜索的性能与Apple的natif罗盘应用程序相同。 例如,当角度通过359到0度时,向notif用户发出振动。但是有时振动不会出现。
我的LocationProvider类:
import SwiftUI
import CoreLocation
import Combine
public class LocationProvider: NSObject,CLLocationmanagerDelegate,ObservableObject {
private let locationmanager: CLLocationmanager
public let heading = PassthroughSubject<CGFloat,Never>()
@Published var currentHeading: CGFloat {
willSet {
heading.send(newValue)
}
}
public override init() {
currentHeading = 0
locationmanager = CLLocationmanager()
super.init()
locationmanager.delegate = self
locationmanager.desiredaccuracy = kCLLocationaccuracyBest
locationmanager.startUpdatingHeading()
locationmanager.requestWhenInUseAuthorization()
}
public func locationmanager(_ manager: CLLocationmanager,didUpdateHeading newHeading: CLHeading) {
self.currentHeading = CGFloat(newHeading.trueHeading)
}
}
我的contentView:
import SwiftUI
import CoreLocation
struct ContentView: View {
@ObservedObject var location: LocationProvider = LocationProvider()
@State var angle: CGFloat = 0
var body: some View {
VStack {
Text(String(Double(-self.location.currentHeading + 360).stringWithoutZeroFraction) + "°")
.font(.system(size: 80))
}
.onReceive(self.location.heading) { heading in
compassTapticFeedback(-heading + 360)
}
}
}
public extension Double {
var stringWithoutZeroFraction: String {
return String(format: "%.0f",self)
}
}
// Taptic feednack
func tapticFeedback(_ type: String) {
switch type {
case "heavy":
let tapticFeedback = UIImpactFeedbackGenerator(style: .heavy)
tapticFeedback.prepare()
tapticFeedback.impactOccurred()
case "medium":
let tapticFeedback = UIImpactFeedbackGenerator(style: .medium)
tapticFeedback.prepare()
tapticFeedback.impactOccurred()
case "light":
let tapticFeedback = UIImpactFeedbackGenerator(style: .light)
tapticFeedback.prepare()
tapticFeedback.impactOccurred()
default:
let tapticFeedback = UIImpactFeedbackGenerator(style: .medium)
tapticFeedback.prepare()
tapticFeedback.impactOccurred()
}
}
func compassTapticFeedback(_ angle: CGFloat) {
switch Int(angle) {
case 0:
tapticFeedback("heavy")
case 30:
tapticFeedback("heavy")
case 60:
tapticFeedback("heavy")
case 90:
tapticFeedback("heavy")
case 120:
tapticFeedback("heavy")
case 250:
tapticFeedback("heavy")
case 180:
tapticFeedback("heavy")
case 210:
tapticFeedback("heavy")
case 240:
tapticFeedback("heavy")
case 270:
tapticFeedback("heavy")
case 300:
tapticFeedback("heavy")
case 330:
tapticFeedback("heavy")
default:
return
}
}
可能是因为我在角度上进行了大量计算以获得没有零分数的值吗?我不知道。即使我不确定是什么原因。