AsyncLocationKit

Swift Package Manager Swift Platforms

苹果 CoreLocation 框架的封装器,采用新的并发模型。不再使用 delegate 模式或 completion blocks

安装


SPM
dependencies: [
    .package(url: "https://github.com/AsyncSwift/AsyncLocationKit.git", .upToNextMinor(from: "1.6.4"))
]

Cocoapods

pod 'AsyncLocationKit', :git => 'https://github.com/AsyncSwift/AsyncLocationKit.git', :tag => '1.6.4'

⚠️ 仅在主线程上同步初始化 AsyncLocationManager

import AsyncLocationKit

let asyncLocationManager = AsyncLocationManager(desiredAccuracy: .bestAccuracy)

let permission = await self.asyncLocationManager.requestAuthorizationWhenInUse() //returns CLAuthorizationStatus

您可以使用所有来自苹果 CLLocationManager 的方法。

let coordinate = try await asyncLocationManager.requestLocation() //Request user location once

使用 AsyncStream 开始监听用户位置更新。

for await locationUpdateEvent in await asyncLocationManager.startUpdatingLocation() {
    switch locationUpdateEvent {
    case .didUpdateLocations(let locations):
        // do something
    case .didFailWith(let error):
        // do something
    case .didPaused, .didResume: 
        break
    }
}

如果 Task 被取消,Stream 会自动完成。