Skip to content

Instantly share code, notes, and snippets.

@ispiropoulos
Last active July 17, 2021 00:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ispiropoulos/a5d0016c970b1bfb31c8c0c54220a588 to your computer and use it in GitHub Desktop.
Save ispiropoulos/a5d0016c970b1bfb31c8c0c54220a588 to your computer and use it in GitHub Desktop.
Store CLLocation into UserDefaults
//
// 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
}
}
@DavidGagne
Copy link

Excellent! Thanks!

@tkhabbab
Copy link

how to use in a different class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment