Async pattern using new concurrency model in swift that can be applied to Core Bluetooth, Core Motion and others sources streaming data asynchronously
if you are using the simulator don't forget to simulate locations
@EnvironmentObject var model: LMViewModel
If task will be canceled the streaming stops automatically. I would recommend to use .task modifier it manages cancelation on it's own. If you need to use Task and keep it in @State don't forget to cancel() when the time has come or it might course memory leaks in some cases
.task{
do{
try await viewModel.start()
}catch{
self.error = error.localizedDescription
}
}
@ViewBuilder
var coordinatesTpl: some View{
List(viewModel.locations, id: \.hash) { location in
Text("\(location.coordinate.longitude), \(location.coordinate.latitude)")
}
}
///Access was denied by user
case accessIsNotAuthorized
/// Attempt to launch streaming while it's been already started
/// Subscribe different Views to LMViewModel.locations publisher to feed them
case streamingProcessHasAlreadyStarted
/// Stream was cancelled
case streamCanceled
/// Stream was terminated
case streamUnknownTermination
/// A Core Location error
case coreLocationManagerError(CLError)
There's been a glitch - throwing CLError.locationUnknown Error Domain=kCLErrorDomain Code=0 "(null)" on some devices and simulator while changing locations time by time. This type of error .locationUnknown is excluded when is happens in delegate method didFailWithError
public protocol ILocationManagerViewModel: ObservableObject{
/// List of locations
@MainActor
var locations : [CLLocation] { get }
/// Strategy for publishing locations Default value is .keepLast
/// .keepAll is an option
var strategy : LMViewModel.Strategy { get }
/// Start streaming locations
func start() async throws
/// Stop streaming locations
func stop()
}
Param | Description |
---|---|
strategy | Strategy for publishing locations Default value is .keepLast The other option is .keepAll |
accuracy | The accuracy of a geographical coordinate. |
activityType | Constants indicating the type of activity associated with location updates. |
distanceFilter | A distance in meters from an existing location. |
backgroundUpdates | A Boolean value that indicates whether the app receives location updates when running in the background |
Available for watchOS
link |
Stars: 16 |
Last commit: 2 weeks ago |
Code refactoring Processing additional errors
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics