Created
March 24, 2016 07:56
-
-
Save aataraxiaa/eca594903710ab032086 to your computer and use it in GitHub Desktop.
How to create a location-based iOS Today Extension using Swift
This file contains 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
// | |
// TodayViewController.swift | |
// LocationTodayExtension | |
// | |
// Created by Pete Smith on 24/03/2016. | |
// Copyright © 2016 Pete Smith. All rights reserved. | |
// | |
import UIKit | |
import NotificationCenter | |
import CoreLocation | |
class TodayViewController: UIViewController { | |
// This is used to indicate whether an update of the today widget is required or not | |
private var updateResult = NCUpdateResult.NoData | |
lazy private var locman = CLLocationManager() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view from its nib. | |
locman.delegate = self | |
} | |
override func viewWillAppear(animated: Bool) { | |
super.viewWillAppear(animated) | |
locman.startUpdatingLocation() | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
// Update our display | |
func updateDisplay() { | |
//... | |
} | |
} | |
typealias WidgetProvider = TodayViewController | |
extension WidgetProvider: NCWidgetProviding { | |
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) { | |
// Perform any setup necessary in order to update the view. | |
// If an error is encountered, use NCUpdateResult.Failed | |
// If there's no update required, use NCUpdateResult.NoData | |
// If there's an update, use NCUpdateResult.NewData | |
completionHandler(updateResult) | |
} | |
} | |
typealias LocationDelegate = TodayViewController | |
extension LocationDelegate: CLLocationManagerDelegate { | |
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { | |
// If we could not retrive location data, set our update result to Failed | |
updateResult = .Failed | |
} | |
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { | |
// Do stuff with the retrieved location, update our display and then set our update result to NewData | |
updateDisplay() | |
updateResult = .NewData | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment