A simple-to-use wrapper for CLLocation for encoding and decoding CLLocation.
A lot of iOS applications work with the Core Location framework. The main object of Core Location is CLLocation, which represents a location. For some odd reason, Core Location doesn't conform to Codable protocol. Therefore, we can't serialize it by default, save it to a database, or send it through a network API. This project solves it.
In this code, I created a wrapper for CLLocation which you can use to serialize and deserialize CLLocation. Enjoy!
P.S. Check the tests to see how it works and how to use CLLocationWrapper.
Let's say you have a location:
import CoreLocation
let location = CLLocation(coordinate: CLLocationCoordinate2D(latitude: 16.6, longitude: 12.5),
altitude: 2.6,
horizontalAccuracy: 1.8,
verticalAccuracy: 9,
course: 46.891,
speed: 1.5,
timestamp: Date())
and you want to serialize it. You can wrap it:
let locationWrapper = CLLocationWrapper(location: location)
and voilĂ ! it's serialized!
Now you can send it to a server, save it in User Defaults, or write it to a database:
let jsonEncoder = JSONEncoder()
do {
let encodedLocationWrapper = try jsonEncoder.encode(locationWrapper.location)
// Do whatever you want with the wrapped location
} catch {
print("Error! Location wrapper encode failed: '\(error)'")
}
And how to decode it?
Very simple:
let jsonDecoder = JSONDecoder()
do {
let decodedLocationWrapper = try jsonDecoder.decode(CLLocationWrapper.self, from: encodedLocationWrapper)
// Do whatever you want with the wrapped location
} catch {
print("Error! Location wrapper decode failed: '\(error)'")
}
CocoaPods manages dependencies for your Xcode projects. For installation instructions and usage, visit their website. To integrate CLLocationWrapper into your Xcode project, specify it in your Podfile
:
pod 'CLLocationWrapper'
The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift
compiler.
Once you have your Swift package set up, adding CLLocationWrapper as a dependency is as easy as adding it to the dependencies
value of your Package.swift
.
dependencies: [
.package(url: "https://github.com/yonivav/CLLocationWrapper.git")
]
If you prefer not to use any of the mentioned dependency managers, you can integrate CLLocationWrapper into your project manually.
You can contribute by adding new features, clarify the current code or fixing bugs. To do so, open a PR. When submitting a pull request, please add tests and ensure your changes don't break any existing tests.
This repository was Inspired by this gist