Last active
July 17, 2021 00:29
-
-
Save ispiropoulos/a5d0016c970b1bfb31c8c0c54220a588 to your computer and use it in GitHub Desktop.
Store CLLocation into UserDefaults
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UserDefaults+CLLocation.swift | |
// | |
// | |
// Created by John Spiropoulos on 28/09/16. | |
// Copyright © 2016 John Spiropoulos. All rights reserved. | |
// | |
/* | |
Swift 3 Helper extension: | |
usage example: | |
Store: UserDefaults.standard.set(location:myLocation, forKey:"myLocation") | |
Retreive: UserDefaults.standad.location(forKey:"myLocation") | |
*/ | |
import CoreLocation | |
import Foundation | |
extension UserDefaults { | |
func set(location:CLLocation, forKey key: String){ | |
let locationLat = NSNumber(value:location.coordinate.latitude) | |
let locationLon = NSNumber(value:location.coordinate.longitude) | |
self.set(["lat": locationLat, "lon": locationLon], forKey:key) | |
} | |
func location(forKey key: String) -> CLLocation? | |
{ | |
if let locationDictionary = self.object(forKey: key) as? Dictionary<String,NSNumber> { | |
let locationLat = locationDictionary["lat"]!.doubleValue | |
let locationLon = locationDictionary["lon"]!.doubleValue | |
return CLLocation(latitude: locationLat, longitude: locationLon) | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Excellent! Thanks!