我不明白我的错误在哪里,因为在我这边,无论是在物理设备上还是在模拟器中,一切都进展顺利。
你看到什么了吗?你能在 Xcode 中测试这个最小的可重现示例并告诉我你发生了什么吗?
// BootcampApp.swift
import SwiftUI
@main
struct BootcampApp: App {
@StateObject private var locationManager = LocationManager()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(locationManager)
}
}
}
// ContentView.swift
import SwiftUI
struct ContentView: View {
@EnvironmentObject private var locationManager: LocationManager
var body: some View {
Group {
if let userLocation = locationManager.userLocation, let cityName = locationManager.cityName {
HomeView(userLocation: userLocation, cityName: cityName)
} else {
WelcomeView()
}
}
}
}
// HomeView.swift
import SwiftUI
import CoreLocation
struct HomeView: View {
let userLocation: CLLocation
let cityName: String
var body: some View {
VStack {
Text("Hello, World!")
}
}
}
// WelcomeView.swift
import SwiftUI
struct WelcomeView: View {
@EnvironmentObject private var locationManager: LocationManager
var body: some View {
VStack {
Button("Allow location", action: { locationManager.requestLocation() })
}
}
}
// LocationManager.swift
import Foundation
import CoreLocation
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
@Published var userLocation: CLLocation?
@Published var cityName: String?
override init() {
super.init()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.distanceFilter = 100
manager.startUpdatingLocation()
}
func requestLocation() {
manager.requestWhenInUseAuthorization()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
userLocation = location
reverseGeocode(location)
}
func reverseGeocode(_ location: CLLocation) {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { placemarks, error in
guard let placemark = placemarks?.first else { return }
self.cityName = placemark.locality
}
}
}
// Info.plist
Privacy - Location When In Use Usage Description => "The app needs your location."
提前谢谢!
NSLocationWhenInUseUsageDescription
在 Info.plist 中而不是“隐私 - 使用时的位置使用说明”字符串中,那么它应该可以正常工作。您可以在这里找到完整的字符串,我已将其添加为书签,因为我更经常需要它。
https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html
在这里您可以找到NSLocationWhenInUseUsageDescription
的文档。
https://developer.apple.com/documentation/bundleresources/information_property_list/nslocationwheninuseusagedescription
我希望这可以帮助你。