Files
suixinkan_uikit/suixinkan/Features/Orders/Utils/OrderLocationProvider.swift

56 lines
1.7 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// OrderLocationProvider.swift
// suixinkan
//
import CoreLocation
///
final class OrderLocationProvider: NSObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
private var continuation: ((Result<CLLocationCoordinate2D, Error>) -> Void)?
override init() {
super.init()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
}
func requestCoordinate() async throws -> CLLocationCoordinate2D {
let status = manager.authorizationStatus
if status == .notDetermined {
manager.requestWhenInUseAuthorization()
}
guard status == .authorizedWhenInUse || status == .authorizedAlways || manager.authorizationStatus == .authorizedWhenInUse else {
throw OrderLocationError.permissionDenied
}
return try await withCheckedThrowingContinuation { continuation in
self.continuation = { result in
continuation.resume(with: result)
}
manager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
continuation?(.success(location.coordinate))
continuation = nil
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
continuation?(.failure(error))
continuation = nil
}
}
enum OrderLocationError: LocalizedError {
case permissionDenied
var errorDescription: String? {
switch self {
case .permissionDenied: "缺少定位权限,功能无法进行"
}
}
}