feat(drone-dock): 接入真实拍摄准备页

This commit is contained in:
2026-10-28 15:05:04 +08:00
parent f7a2a19dee
commit 79884cf588
12 changed files with 2041 additions and 39 deletions
@@ -0,0 +1,32 @@
import Foundation
/// 拍摄准备页只读数据源,不创建订单任务或发送飞行控制指令。
protocol DroneDockPreparationServing: Sendable {
/// 获取指定订单的点位、航线与召唤门禁;无有效定位时省略坐标。
@MainActor
func workbench(scenicID: Int, orderNumber: String, coordinate: DroneDockPreparationCoordinate?) async throws -> DroneDockPreparationResponse
}
/// 朱工的拍摄准备接口,登录凭证由统一客户端注入。
@MainActor
final class DroneDockPreparationAPI: DroneDockPreparationServing {
private let client: APIClient
/// 注入统一客户端,正式页面和测试使用相同请求构造。
init(client: APIClient) { self.client = client }
/// 只读取准备快照,未知位置不会补零或替换成景区坐标。
func workbench(scenicID: Int, orderNumber: String, coordinate: DroneDockPreparationCoordinate?) async throws -> DroneDockPreparationResponse {
guard scenicID > 0, !orderNumber.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw APIError.networkFailed("缺少当前景区或订单信息,请返回重试")
}
var query = [URLQueryItem(name: "scenic_id", value: String(scenicID)),
URLQueryItem(name: "order_number", value: orderNumber)]
if let coordinate {
guard coordinate.isValid else { throw APIError.networkFailed("定位结果无效,请重新定位") }
query.append(URLQueryItem(name: "lat", value: String(coordinate.latitude)))
query.append(URLQueryItem(name: "lng", value: String(coordinate.longitude)))
}
return try await client.send(APIRequest(method: .get, path: "/api/app/airport/workbench", queryItems: query))
}
}
@@ -0,0 +1,247 @@
import Foundation
/// 本次定位得到的准备页坐标;未知位置使用 nil,不以零坐标替代。
struct DroneDockPreparationCoordinate: Equatable, Sendable {
/// 定位服务返回的纬度。
let latitude: Double
/// 定位服务返回的经度。
let longitude: Double
/// 保存一次实际定位结果,发送请求前再校验有效性。
init(latitude: Double, longitude: Double) {
self.latitude = latitude
self.longitude = longitude
}
/// 仅接受有限且处于地理范围内的坐标,拒绝未定位时常见的零点占位。
var isValid: Bool {
latitude.isFinite && longitude.isFinite
&& (-90...90).contains(latitude) && (-180...180).contains(longitude)
&& (latitude != 0 || longitude != 0)
}
}
/// 朱工 workbench 的真实准备快照,仅描述当前订单、点位航线与服务端许可。
struct DroneDockPreparationResponse: Decodable, Equatable, Sendable {
/// 响应所属景区。
let scenicID: Int
/// 响应所属订单号。
let orderNumber: String
/// 服务端最新订单进度;缺失时不沿用旧额度。
let orderProgress: DroneDockPreparationOrderProgress?
/// 真实机巢摘要,不将它等同于已派机结果。
let airports: [DroneDockHomeAirport]
/// 该订单的拍摄点位,保持服务端顺序。
let spots: [DroneDockPreparationSpot]
/// 后端召唤许可快照,缺失时保持未知。
let shootGate: DroneDockPreparationShootGate?
/// 后端规则提示原文。
let tips: String?
/// workbench 已验证的顶层字段。
private enum CodingKeys: String, CodingKey {
case scenicID = "scenic_id", orderNumber = "order_number", orderProgress = "order_progress"
case airports, spots, shootGate = "shoot_gate", tips
}
/// 严格读取订单范围和列表身份,避免坏响应伪装成成功空态或破坏 Diffable 更新。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
scenicID = try container.positivePreparationID(forKey: .scenicID)
orderNumber = try container.decode(String.self, forKey: .orderNumber)
guard !orderNumber.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw DecodingError.dataCorruptedError(forKey: .orderNumber, in: container, debugDescription: "订单号不能为空")
}
orderProgress = try container.decodeIfPresent(DroneDockPreparationOrderProgress.self, forKey: .orderProgress)
if let progressOrder = orderProgress?.orderNumber, progressOrder != orderNumber {
throw DecodingError.dataCorruptedError(forKey: .orderProgress, in: container, debugDescription: "订单进度与当前订单不一致")
}
airports = try container.decode([DroneDockHomeAirport].self, forKey: .airports)
guard Set(airports.map(\.id)).count == airports.count else {
throw DecodingError.dataCorruptedError(forKey: .airports, in: container, debugDescription: "设备 ID 重复")
}
spots = try container.decode([DroneDockPreparationSpot].self, forKey: .spots)
guard Set(spots.map(\.id)).count == spots.count else {
throw DecodingError.dataCorruptedError(forKey: .spots, in: container, debugDescription: "拍摄点 ID 重复")
}
shootGate = try container.decodeIfPresent(DroneDockPreparationShootGate.self, forKey: .shootGate)
tips = try container.decodeIfPresent(String.self, forKey: .tips)
}
}
/// 准备页服务端订单进度,不在客户端推算剩余次数或扣减额度。
struct DroneDockPreparationOrderProgress: Decodable, Equatable, Sendable {
/// 进度所属订单号,存在时需与顶层一致。
let orderNumber: String?
/// 服务端套餐说明。
let packageName: String?
/// 服务端拍摄总次数。
let shotTotal: Int?
/// 服务端已拍次数,保留合法零值。
let shotUsed: Int?
/// 服务端剩余次数,缺失时保持未知。
let shotRemain: Int?
/// 服务端订单状态文案。
let statusLabel: String?
/// 订单进度字段名。
private enum CodingKeys: String, CodingKey {
case orderNumber = "order_number", packageName = "package_name", shotTotal = "shot_total"
case shotUsed = "shot_used", shotRemain = "shot_remain", statusLabel = "status_label"
}
/// 兼容整数及整数字符串,同时区分未知次数与零次。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
orderNumber = try container.decodeIfPresent(String.self, forKey: .orderNumber)
packageName = try container.decodeIfPresent(String.self, forKey: .packageName)
shotTotal = try container.preparationCountIfPresent(forKey: .shotTotal)
shotUsed = try container.preparationCountIfPresent(forKey: .shotUsed)
shotRemain = try container.preparationCountIfPresent(forKey: .shotRemain)
statusLabel = try container.decodeIfPresent(String.self, forKey: .statusLabel)
}
}
/// 拍摄点的服务端距离、已拍状态与可选航线;距离是否可用由请求是否带定位决定。
struct DroneDockPreparationSpot: Decodable, Equatable, Sendable {
/// 拍摄点稳定 ID。
let id: Int
/// 拍摄点名称。
let name: String
/// 服务端格式化距离,不自行换算距离文案。
let distanceLabel: String?
/// 服务端距离米数。
let distanceM: Double?
/// 服务端范围判断,缺失时不默认在范围内。
let inRange: Bool?
/// 本点位已拍次数。
let shotCount: Int?
/// 本点位已拍状态文案。
let shotStatusLabel: String?
/// 点位所属航线,按后端顺序展示。
let airLines: [DroneDockPreparationAirLine]
/// 已验证的点位字段名。
private enum CodingKeys: String, CodingKey {
case id = "scenic_spot_id", name, distanceLabel = "distance_label", distanceM = "distance_m"
case inRange = "in_range", shotCount = "shot_count", shotStatusLabel = "shot_status_label", airLines = "air_lines"
}
/// 点位和航线身份必须有效且点位内唯一,缺失距离与次数保留未知。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.positivePreparationID(forKey: .id)
name = try container.decode(String.self, forKey: .name)
distanceLabel = try container.decodeIfPresent(String.self, forKey: .distanceLabel)
distanceM = try container.decodeIfPresent(DroneDockPreparationNumber.self, forKey: .distanceM)?.value
if let distanceM, distanceM < 0 {
throw DecodingError.dataCorruptedError(forKey: .distanceM, in: container, debugDescription: "距离不能为负数")
}
inRange = try container.decodeIfPresent(Bool.self, forKey: .inRange)
shotCount = try container.preparationCountIfPresent(forKey: .shotCount)
shotStatusLabel = try container.decodeIfPresent(String.self, forKey: .shotStatusLabel)
airLines = try container.decode([DroneDockPreparationAirLine].self, forKey: .airLines)
guard Set(airLines.map(\.id)).count == airLines.count else {
throw DecodingError.dataCorruptedError(forKey: .airLines, in: container, debugDescription: "点位内航线 ID 重复")
}
}
}
/// 准备页返回的航线信息;不从飞行类型或时长推断设备执行许可。
struct DroneDockPreparationAirLine: Decodable, Equatable, Sendable {
/// 航线稳定 ID。
let id: Int
/// 航线名称。
let name: String
/// 服务端预计飞行时长原值。
let estimatedFlyTime: Int?
/// 服务端航线视频时长原值。
let lineVideoDuration: Int?
/// 服务端飞行类型原值。
let flyType: Int?
/// 已验证的航线字段名。
private enum CodingKeys: String, CodingKey {
case id = "air_line_id", name, estimatedFlyTime = "estimated_fly_time"
case lineVideoDuration = "line_video_duration", flyType = "fly_type"
}
/// 航线 ID 必须有效,时长未知时不显示伪造零值。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.positivePreparationID(forKey: .id)
name = try container.decode(String.self, forKey: .name)
estimatedFlyTime = try container.preparationCountIfPresent(forKey: .estimatedFlyTime)
lineVideoDuration = try container.preparationCountIfPresent(forKey: .lineVideoDuration)
flyType = try container.decodeIfPresent(DroneDockPreparationInteger.self, forKey: .flyType)?.value
}
}
/// 后端召唤门禁,仅提供当前许可与原因,不等于客户端已实现或执行召唤。
struct DroneDockPreparationShootGate: Decodable, Equatable, Sendable {
/// 后端明确允许召唤时为 true,缺失仍为未知。
let canShoot: Bool?
/// 后端门禁代码,保留未知新值。
let code: String?
/// 后端原因说明。
let message: String?
/// 后端主操作标识。
let primaryAction: String?
/// 后端主操作文案。
let primaryActionLabel: String?
/// 门禁字段名。
private enum CodingKeys: String, CodingKey {
case canShoot = "can_shoot", code, message
case primaryAction = "primary_action", primaryActionLabel = "primary_action_label"
}
}
/// 本接口整数与整数字符串的兼容读取器,不接受布尔、分数或部分数字。
private struct DroneDockPreparationInteger: Decodable {
let value: Int
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let number = try? container.decode(Int.self) { value = number }
else if let text = try? container.decode(String.self), let number = Int(text) { value = number }
else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "需要整数或整数字符串") }
}
}
/// 本接口距离数字的兼容读取器,不接受非有限值。
private struct DroneDockPreparationNumber: Decodable {
let value: Double
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let number: Double
if let decoded = try? container.decode(Double.self) { number = decoded }
else if let text = try? container.decode(String.self), let decoded = Double(text) { number = decoded }
else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "需要数字或数字字符串") }
guard number.isFinite else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "数字必须为有限值")
}
value = number
}
}
private extension KeyedDecodingContainer {
/// 读取会作为列表身份的正整数。
func positivePreparationID(forKey key: Key) throws -> Int {
let value = try decode(DroneDockPreparationInteger.self, forKey: key).value
guard value > 0 else {
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "ID 必须为正整数")
}
return value
}
/// 读取可缺失的非负次数或时长。
func preparationCountIfPresent(forKey key: Key) throws -> Int? {
guard let value = try decodeIfPresent(DroneDockPreparationInteger.self, forKey: key)?.value else { return nil }
guard value >= 0 else {
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "次数或时长不能为负数")
}
return value
}
}
@@ -0,0 +1,200 @@
import CoreLocation
import Foundation
/// 真实拍摄准备状态:读取订单、定位和点位航线,选择过程不创建或执行飞行任务。
final class DroneDockPreparationViewModel {
/// 页面进入时固定的账号、景区及门店范围。
let context: DroneDockHomeContext
/// 首页选中的真实订单,仅用于身份及进入时的摘要展示。
let order: DroneDockHomeOrder
/// 最新通过身份校验的准备信息。
private(set) var response: DroneDockPreparationResponse?
/// 是否正在定位或读取准备信息。
private(set) var isLoading = false
/// 加载失败或身份改变时的提示。
private(set) var errorMessage: String?
/// 没有取得有效位置时的说明,不使用后端无坐标时返回的距离。
private(set) var locationMessage: String?
/// 当前响应是否基于本次成功定位的坐标。
private(set) var hasLocation = false
/// 当前点位与航线的稳定身份。
private(set) var selectedSpotID: Int?
/// 航线只属于当前选中的点位。
private(set) var selectedRouteID: Int?
private let service: any DroneDockPreparationServing
private let locationProvider: any LocationProviding
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private var generation = 0
/// 注入真实只读接口、可替换定位服务和最新登录范围。
init(context: DroneDockHomeContext, order: DroneDockHomeOrder,
service: any DroneDockPreparationServing, locationProvider: any LocationProviding,
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.order = order
self.service = service
self.locationProvider = locationProvider
self.currentContext = currentContext
}
/// 当前订单的点位,保持服务端顺序。
var spots: [DroneDockPreparationSpot] { response?.spots ?? [] }
/// 当前选中点位,刷新后不再存在时会重新选择。
var selectedSpot: DroneDockPreparationSpot? { spots.first { $0.id == selectedSpotID } }
/// 只展示当前点位所属的航线。
var routes: [DroneDockPreparationAirLine] { selectedSpot?.airLines ?? [] }
/// 当前选中航线,不跨点位保留旧选择。
var selectedRoute: DroneDockPreparationAirLine? { routes.first { $0.id == selectedRouteID } }
/// 获取一次位置和准备快照;定位失败仍可浏览点位航线,但范围保持未知。
func refresh() async {
generation &+= 1
let requestGeneration = generation
isLoading = true
errorMessage = nil
locationMessage = nil
hasLocation = false
defer { if generation == requestGeneration { isLoading = false } }
guard await accepts(requestGeneration) else { return }
guard context.canLoad, let number = DroneDockHomeMetric.usableText(order.orderNumber) else {
clearResponse()
errorMessage = "缺少当前景区或订单信息,请返回工作台重新进入"
return
}
var coordinate: DroneDockPreparationCoordinate?
do {
let result = try await locationProvider.requestCoordinate(desiredAccuracy: kCLLocationAccuracyBest)
let value = DroneDockPreparationCoordinate(latitude: result.latitude, longitude: result.longitude)
guard value.isValid else { throw LocationProviderError.locationFailed }
coordinate = value
} catch {
guard await accepts(requestGeneration) else { return }
locationMessage = "\(error.localizedDescription),距离和拍摄范围待确认"
}
guard await accepts(requestGeneration) else { return }
do {
let result = try await service.workbench(scenicID: context.scenicID, orderNumber: number, coordinate: coordinate)
guard await accepts(requestGeneration) else { return }
guard result.scenicID == context.scenicID, result.orderNumber == number,
result.orderProgress?.orderNumber == nil || result.orderProgress?.orderNumber == number else {
clearResponse()
errorMessage = "接口返回的景区或订单与当前订单不一致,请刷新重试"
return
}
response = result
hasLocation = coordinate != nil
if !spots.contains(where: { $0.id == selectedSpotID }) { selectedSpotID = spots.first?.id }
if !routes.contains(where: { $0.id == selectedRouteID }) { selectedRouteID = routes.first?.id }
} catch {
guard await accepts(requestGeneration) else { return }
clearResponse()
errorMessage = error.localizedDescription
}
}
/// 选择现有点位,切点后航线重置为该点位的第一条,不复用另一点位的航线。
func selectSpot(id: Int) {
guard !isLoading, spots.contains(where: { $0.id == id }), selectedSpotID != id else { return }
selectedSpotID = id
selectedRouteID = routes.first?.id
}
/// 选择当前点位中的航线,忽略过期或不属于该点位的点击。
func selectRoute(id: Int) {
guard !isLoading, routes.contains(where: { $0.id == id }) else { return }
selectedRouteID = id
}
/// 页面离开后使定位和网络的迟到结果失效。
func invalidate() {
generation &+= 1
isLoading = false
errorMessage = nil
locationMessage = nil
clearResponse()
}
/// 根据实际机巢摘要展示连接状态,不将 can_shoot 当作设备连接证明。
var connectionTitle: String {
guard let airports = response?.airports, !airports.isEmpty else { return "机巢连接待确认" }
if airports.contains(where: { $0.onlineStatus == 1 }) { return "有机巢在线" }
if airports.allSatisfy({ $0.onlineStatus == 2 }) { return "机巢未连接" }
return "机巢连接待确认"
}
/// 只为明确在线的设备摘要显示绿色状态。
var connectionTone: DroneDockStatusTone {
response?.airports.contains(where: { $0.onlineStatus == 1 }) == true ? .green : .gray
}
/// 只有请求携带有效定位时才采用服务端范围结论。
var rangeTitle: String {
guard hasLocation else { return "位置待确认" }
guard let selectedSpot else { return "请选择拍摄点" }
switch selectedSpot.inRange {
case true: return "在拍摄范围内"
case false: return "不在拍摄范围内"
default: return "拍摄范围待确认"
}
}
/// 未知位置或范围不显示绿色。
var rangeTone: DroneDockStatusTone { hasLocation && selectedSpot?.inRange == true ? .green : .gray }
/// 当前航线选择的展示摘要。
var selectionSummary: String {
guard let selectedSpot else { return "请选择拍摄点" }
guard let selectedRoute else { return "\(selectedSpot.name) · 未选航线" }
return "\(selectedSpot.name) · \(selectedRoute.name)"
}
/// 多机状态一致时展示该状态,不假定某台机巢已被选派。
var deviceStatusText: String {
let labels = Set(response?.airports.map(\.statusTitle) ?? [])
return labels.count == 1 ? labels.first! : "状态待确认"
}
/// 准备阶段尚未派机,状态标签使用中性色。
var deviceTone: DroneDockStatusTone { .gray }
/// 保留后端明确的阻止原因,允许准备时展示下一步按钮标题。
var primaryButtonTitle: String {
if let gate = response?.shootGate, gate.canShoot == false {
return DroneDockHomeMetric.usableText(gate.primaryActionLabel) ?? "暂不可召唤"
}
return "确认并召唤"
}
/// 展示当前阻止原因;本阶段仅对接准备信息,不发送召唤指令。
var admissionMessage: String {
if isLoading { return "正在获取位置和拍摄准备信息" }
if let errorMessage { return errorMessage }
guard let response else { return "正在加载拍摄准备信息" }
if let gate = response.shootGate, gate.canShoot == false {
return DroneDockHomeMetric.usableText(gate.message)
?? DroneDockHomeMetric.usableText(gate.primaryActionLabel) ?? "当前暂不可召唤,请刷新状态"
}
if let locationMessage { return locationMessage }
if spots.isEmpty { return "当前暂无可用拍摄点" }
if routes.isEmpty { return "当前拍摄点暂无可用航线" }
if !hasLocation || selectedSpot?.inRange == nil { return "拍摄范围待确认,请重新定位" }
if selectedSpot?.inRange == false { return "请前往所选拍摄点的拍摄范围内" }
guard response.shootGate?.canShoot == true else { return "拍摄条件待确认,请刷新状态" }
return "召唤功能暂未开放"
}
private func clearResponse() {
response = nil
selectedSpotID = nil
selectedRouteID = nil
hasLocation = false
}
private func accepts(_ requestGeneration: Int) async -> Bool {
guard generation == requestGeneration, !Task.isCancelled else { return false }
let latest = await currentContext()
guard generation == requestGeneration, !Task.isCancelled else { return false }
guard context.hasSameIdentity(as: latest) else {
generation &+= 1
isLoading = false
clearResponse()
errorMessage = "账号或景区已变化,请返回工作台重新进入"
return false
}
return true
}
}
@@ -17,6 +17,8 @@ protocol CoreLocationManaging: AnyObject {
func requestWhenInUseAuthorization()
/// 请求一次当前位置。
func requestLocation()
/// 结束已取消或已超时的定位,释放系统中的单次请求。
func stopUpdatingLocation()
}
extension CLLocationManager: CoreLocationManaging {}
@@ -31,7 +33,11 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
private var manager: any CoreLocationManaging = CLLocationManager()
private var geocoder: any LocationAddressGeocoding = LocationGeocoder.shared
private var permissionContinuation: CheckedContinuation<Void, Error>?
private var permissionRequestID: UUID?
private var locationContinuation: CheckedContinuation<CLLocationCoordinate2D, Error>?
private var locationRequestID: UUID?
private var locationTimeoutTask: Task<Void, Never>?
private var locationTimeoutNanoseconds: UInt64 = 10_000_000_000
nonisolated override init() {
super.init()
@@ -41,11 +47,13 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
init(
appStore: AppStore,
manager: any CoreLocationManaging,
geocoder: any LocationAddressGeocoding
geocoder: any LocationAddressGeocoding,
locationTimeoutNanoseconds: UInt64 = 10_000_000_000
) {
self.appStore = appStore
self.manager = manager
self.geocoder = geocoder
self.locationTimeoutNanoseconds = max(1, locationTimeoutNanoseconds)
super.init()
manager.delegate = self
}
@@ -66,21 +74,41 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
)
}
/// 请求一次当前位置坐标。
/// 请求一次当前位置坐标;系统未回调时超时结束,调用方取消时清理本次等待。
func requestCoordinate(
desiredAccuracy: CLLocationAccuracy
) async throws -> CLLocationCoordinate2D {
try Task.checkCancellation()
try requirePrivacyAgreement()
try await ensureLocationPermission()
try Task.checkCancellation()
guard locationContinuation == nil else {
throw LocationProviderError.locationFailed
}
manager.delegate = self
manager.desiredAccuracy = desiredAccuracy
return try await withCheckedThrowingContinuation { continuation in
locationContinuation = continuation
manager.requestLocation()
let requestID = UUID()
let timeout = locationTimeoutNanoseconds
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
guard !Task.isCancelled else {
continuation.resume(throwing: CancellationError())
return
}
locationRequestID = requestID
locationContinuation = continuation
locationTimeoutTask = Task { @MainActor [weak self] in
do { try await Task.sleep(nanoseconds: timeout) }
catch { return }
self?.finishLocation(requestID: requestID, result: .failure(LocationProviderError.locationFailed))
}
manager.requestLocation()
}
} onCancel: {
Task { @MainActor [weak self] in
self?.finishLocation(requestID: requestID, result: .failure(CancellationError()))
}
}
}
@@ -92,6 +120,7 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
/// 请求系统定位权限,等待用户完成首次授权。
func ensureLocationPermission() async throws {
try Task.checkCancellation()
manager.delegate = self
switch manager.authorizationStatus {
case .authorizedAlways, .authorizedWhenInUse:
@@ -102,9 +131,21 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
guard permissionContinuation == nil else {
throw LocationProviderError.locationFailed
}
try await withCheckedThrowingContinuation { continuation in
permissionContinuation = continuation
manager.requestWhenInUseAuthorization()
let requestID = UUID()
try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
guard !Task.isCancelled else {
continuation.resume(throwing: CancellationError())
return
}
permissionRequestID = requestID
permissionContinuation = continuation
manager.requestWhenInUseAuthorization()
}
} onCancel: {
Task { @MainActor [weak self] in
self?.finishPermission(requestID: requestID, result: .failure(CancellationError()))
}
}
@unknown default:
throw LocationProviderError.permissionDenied
@@ -116,21 +157,19 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let continuation = locationContinuation else { return }
locationContinuation = nil
guard let requestID = locationRequestID else { return }
guard let coordinate = locations.last?.coordinate,
CLLocationCoordinate2DIsValid(coordinate),
coordinate.latitude != 0 || coordinate.longitude != 0 else {
continuation.resume(throwing: LocationProviderError.locationFailed)
finishLocation(requestID: requestID, result: .failure(LocationProviderError.locationFailed))
return
}
continuation.resume(returning: coordinate)
finishLocation(requestID: requestID, result: .success(coordinate))
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
guard let continuation = locationContinuation else { return }
locationContinuation = nil
continuation.resume(throwing: LocationProviderError.locationFailed)
guard let requestID = locationRequestID else { return }
finishLocation(requestID: requestID, result: .failure(LocationProviderError.locationFailed))
}
private func requirePrivacyAgreement() throws {
@@ -140,21 +179,37 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
}
private func resolvePermission(status: CLAuthorizationStatus) {
guard let continuation = permissionContinuation else { return }
guard let requestID = permissionRequestID else { return }
switch status {
case .authorizedAlways, .authorizedWhenInUse:
permissionContinuation = nil
continuation.resume()
finishPermission(requestID: requestID, result: .success(()))
case .denied, .restricted:
permissionContinuation = nil
continuation.resume(throwing: LocationProviderError.permissionDenied)
finishPermission(requestID: requestID, result: .failure(LocationProviderError.permissionDenied))
case .notDetermined:
break
@unknown default:
permissionContinuation = nil
continuation.resume(throwing: LocationProviderError.permissionDenied)
finishPermission(requestID: requestID, result: .failure(LocationProviderError.permissionDenied))
}
}
/// 仅结束匹配的授权等待,旧任务的取消不能清除后续请求。
private func finishPermission(requestID: UUID, result: Result<Void, Error>) {
guard permissionRequestID == requestID, let continuation = permissionContinuation else { return }
permissionRequestID = nil
permissionContinuation = nil
continuation.resume(with: result)
}
/// 统一处理成功、失败、超时和取消,先清理状态再恢复等待中的调用方。
private func finishLocation(requestID: UUID, result: Result<CLLocationCoordinate2D, Error>) {
guard locationRequestID == requestID, let continuation = locationContinuation else { return }
locationRequestID = nil
locationContinuation = nil
locationTimeoutTask?.cancel()
locationTimeoutTask = nil
manager.stopUpdatingLocation()
continuation.resume(with: result)
}
}
#if targetEnvironment(simulator)