Skip to content

Instantly share code, notes, and snippets.

@fuxingloh
Created November 15, 2015 06:36
Show Gist options
  • Select an option

  • Save fuxingloh/5470dcbb6c0518891f5d to your computer and use it in GitHub Desktop.

Select an option

Save fuxingloh/5470dcbb6c0518891f5d to your computer and use it in GitHub Desktop.
iOS Swift: Location Awareness, do task when location data is provided.
//
// Awareness.swift
// Edible
//
// Created by Fuxing on 7/5/15.
// Copyright (c) 2015 3Lines. All rights reserved.
//
import Foundation
import CoreLocation
import UIKit
import MapKit
class Awareness{
static var location: CLLocation?
class func distance(locationB: CLLocation) -> String?{
if let location = location{
let mdf = MKDistanceFormatter()
mdf.units = .Metric
return mdf.stringFromDistance(location.distanceFromLocation(locationB))
}
return nil
}
class func distanceInMeter(locationB: CLLocation) -> Double?{
if let location = location{
return location.distanceFromLocation(locationB)
}
return nil
}
// 5km per hour, 83m per minute, due to road complication, 120
class func minuteWalkAway(locationB: CLLocation) -> String?{
if let meter = distanceInMeter(locationB){
let minute = Int(round(meter/120))
if (minute == 0){
return "< 0 mins walk"
}else{
return "\(minute) mins walk"
}
}
return nil
}
class func update(newLocation: CLLocation){
location = newLocation
// Check queue and excute tasks
while(taskQueue.count > 0){
let latLng = getLatLng()
taskQueue.removeLast()(lat: latLng.0, lng: latLng.1)
}
}
class func getLatLng() -> (Double, Double){
if let location = location{
return (location.coordinate.latitude, location.coordinate.longitude)
}
return (0, 0)
}
// Get Awareness, can be empty if latLng are empty
class func get() -> [String: AnyObject]{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
dateFormatter.timeZone = NSTimeZone()
// let localDate = dateFormatter.stringFromDate(NSDate())
if let location = location{
return ["lat": location.coordinate.latitude, "lng": location.coordinate.longitude, "time": dateFormatter.stringFromDate(NSDate())]
}
return ["time": dateFormatter.stringFromDate(NSDate())]
}
// Type alias for queue task
typealias QueueTask = (lat: Double, lng: Double) -> Void
// Queue list
static var taskQueue = [QueueTask]()
// Run func when awareness is available
class func runWhenAwarenessAvailable(task: QueueTask){
if let _ = location{
// Lat lng exist
let latLng = getLatLng()
task(lat: latLng.0, lng: latLng.1)
}else{
// Add task to queue
taskQueue.append(task)
}
}
class func runWhenAvailable(task: QueueTask){
if let _ = location{
// Lat lng exist
let latLng = getLatLng()
task(lat: latLng.0, lng: latLng.1)
}else{
// Add task to queue
taskQueue.append(task)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment