我想使用Swift获取一个位置的当前经度和纬度并显示它们。
如果我将方案更新为具有默认位置,那么它始终只使用默认位置,从不更新我的当前位置,当我在实际设备上尝试时也是如此。请帮忙。
struct prayer: Hashable {
var name: String
var time: String
var color: String
}
LocationFetcher
class LocationFetcher: NSObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
var location: CLLocationCoordinate2D?
override init() {
super.init()
manager.delegate = self
}
func start() {
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
location = locations.first?.coordinate
} }
ContentView
struct ContentView: View {
@State var prayers = [
prayer(name: "Fajr", time: "", color: "Fajr"),
prayer(name: "Sunrise", time: "", color: "Sunrise"),
prayer(name: "Dhuhr", time: "", color: "Dhuhr"),
prayer(name: "Asr", time: "", color: "Asr"),
prayer(name: "Maghrib", time: "", color: "Maghrib"),
prayer(name: "Isha", time: "", color: "Isha")
]
@State var date = ""
@State var currentSalah = ""
@State var nextSalah = ""
@State var country = ""
let locationManager = LocationFetcher()
var body: some View {
ZStack {
Color("Background").ignoresSafeArea()
VStack {
Text(country)
.padding([.top, .bottom], 20)
.foregroundColor(Color.white.opacity(0.7))
.font(.title3)
Text(currentSalah)
.foregroundColor(.white)
.fontWeight(.light)
.padding(.bottom, 15)
.font(.title)
Text(nextSalah)
.foregroundColor(Color.white.opacity(0.7))
.padding(.bottom, 30)
Text(date)
.foregroundColor(.white)
.fontWeight(.light)
ForEach(prayers, id: .self) { prayer in
HStack {
Image(systemName: "deskclock.fill")
.resizable()
.frame(width: 25, height: 25, alignment: .center)
.padding()
.foregroundColor(Color(prayer.color))
Text(prayer.name)
.font(.title)
.fontWeight(.regular)
.foregroundColor(Color(prayer.color))
Spacer()
Text(prayer.time)
.font(.title3)
.fontWeight(.medium)
.padding()
.foregroundColor(Color(prayer.color))
}
.padding(.all, 10)
}
Spacer()
}
}
.onAppear() {
locationManager.start()
getPrayerTime()
}
}
func getPrayerTime() {
let cal = Calendar(identifier: Calendar.Identifier.gregorian)
let date = cal.dateComponents([.year, .month, .day], from: Date())
let coordinates = Coordinates(latitude: locationManager.location?.latitude ?? 33.3152, longitude: locationManager.location?.longitude ?? 44.3661)
var params = CalculationMethod.ummAlQura.params
params.madhab = .hanafi
if let prayers = PrayerTimes(coordinates: coordinates, date: date, calculationParameters: params) {
let formatter = DateFormatter()
formatter.timeStyle = .short
formatter.timeZone = TimeZone(identifier: "America/New_York")!
self.prayers[0].time = formatter.string(from: prayers.fajr)
self.prayers[1].time = formatter.string(from: prayers.sunrise)
self.prayers[2].time = formatter.string(from: prayers.dhuhr)
self.prayers[3].time = formatter.string(from: prayers.asr)
self.prayers[4].time = formatter.string(from: prayers.maghrib)
self.prayers[5].time = formatter.string(from: prayers.isha)
self.updateDate()
self.updateLocationName()
self.updateLabel(prayerTimes: prayers)
}
}
func updateDate() {
let hijriCalendar = Calendar(identifier: .islamicCivil)
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en")
formatter.calendar = hijriCalendar
formatter.dateFormat = "-------- EEEE, MMM dd, yyyy -------- "
date = "(formatter.string(from: Date()))"
}
func updateLabel(prayerTimes: PrayerTimes) {
guard let current = prayerTimes.currentPrayer() else { return }
currentSalah = "Time For (current)"
guard let next = prayerTimes.nextPrayer() else { return }
let countdown = prayerTimes.time(for: next)
let diffTime = countdown.timeIntervalSince(Date())
let diffTimeMin = diffTime / 60
let diffTimeMinRem = Int(diffTimeMin.truncatingRemainder(dividingBy: 60))
let diffTimeHour = Int(diffTimeMin / 60)
let stringDiff = "(next) is in (diffTimeHour) hr, (diffTimeMinRem) min"
print(nextSalah = stringDiff)
}
func updateLocationName() {
let location = CLLocation(latitude: locationManager.location?.latitude ?? 33.3152, longitude: locationManager.location?.longitude ?? 44.3661)
CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in
guard let placemark = placemarks?.first else { return }
country = placemark.country ?? ""
}
} }
您可以尝试使用此
class ContentViewModel: NSObject, ObservableObject, CLLocationManagerDelegate{
@Published var longitudeStorage : Double = 0.0
@Published var latitudeStorage : Double = 0.0
@Published var isTrue : Bool = false
@Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40, longitude: 120), span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100))
let locationManager = CLLocationManager()
override init() {
super.init()
locationManager.delegate = self
}
func requestAllowOnceLocationPermission() {
locationManager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let latestLocation = locations.first else{
//Show an error
return
}
DispatchQueue.main.async {
self.region = MKCoordinateRegion(center: latestLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.015, longitudeDelta: 0.015))
//check region value
print(self.region.center.longitude)
self.longitudeStorage = Double(self.region.center.longitude)
self.latitudeStorage = Double(self.region.center.latitude)
print("Longitude --> (self.longitudeStorage)")
print("Latitude --> (self.latitudeStorage)")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}
}
我正在制作一个变量,它将存储你得到的经度和纬度