具有并发性的快速包包装核心位置

快速位置

CoreLocation 框架上的包装器将委托模式替换为 Swift 并发。

安装

  1. 将包添加到文件中的依赖项。Package.swift

let package = Package(
    ...
    dependencies: [
        .package(url: "https://github.com/alexandrehsaad/swift-locations.git", branch: "main")
    ],
    ...
)
  1. 将包添加为文件中目标的依赖项。Package.swift

let package = Package(
    ...
    targets: [
        .target(name: "MyTarget", dependencies: [
            .product(name: "Locations", package: "swift-locations")
        ]),
    ],
    ...
)
  1. 在源代码中导入包。
import Locations

示范

  1. 以您想要的精度启动管理器。
let manager: LocationManager = .init(accuracy: .tenMetres)
  1. 请求用户使用定位服务的权限,并对收到的异步值执行某些操作。您不能向用户显示两次授权对话框,但可以从“设置”中显示更改权限的步骤。

do {
    let status: AuthorizationStatus = try await manager.requestAlwaysAuthorization()
    // Do something with the status.
    print(status)
} catch let error {
    // Do something with the error.
    print(error)
}
  1. Subscribe to the locater and do something with the asynchronous stream of values you receive. The return type is from the CoreLocation framework.CLLocation

do {
    let stream: AsyncStream<CLLocation> = try manager.subscribeToLocater()
    for await data in stream {
        // Do something with the data.
        print(data)
    }
} catch let error {
    // Do something with the error.
    print(error)
}
  1. Unsubscribe from the locater.
manager.unsubscribeFromLocater()

Troubleshooting

Your app must include usage description keys in its file for the types of data it needs. Failure to include these keys cause the app to crash. To access location data specifically, it must include either or .Info.plistNSLocationWhenInUseUsageDescriptionNSLocationAlwaysAndWhenInUseUsageDescription

Roadmap

You can use this framework to track large or small changes in the user’s current location with a configurable degree of accuracy. It could be extended to support region monitoring, beacon ranging and compass headings.

Contribution

Reporting a bug

If you find a bug, please create an issue.

Contacting the maintainers

The current code owner of this repository is Alexandre H. Saad (@alexandrehsaad). You can contact him by writing an email to alexandresaad at icloud dot com.

Support

If you like my work, show your support by staring this repository.

Feedback

I would love to hear your thoughts or feedback on how Swift Locations could be improved!

GitHub

点击跳转