I am building an app with location services.
I am using users current location to get objects around user. Which is currently working perfectly. The only problem is, I want to create local notifications for user with "signficantLocationChanges" on background but when app launches from AppDelegate with applicationDidFinishLaunching(_:) function, launchOptions object is nil.
I want to get background updates and make an HTTP API request and depending on response, I will create local notification.
Here is my AppDelegate class:
import UIKit
import UserNotifications
import CoreLocation
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var locationManager: LocationManager?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Checking this because if the app is started for location updates,
// no need to setup app for UI
if let _ = launchOptions?[.location] {
locationManager = LocationManager()
locationManager?.delegate = self
locationManager?.getCurrentLocation()
return true
}
attemptToRegisterForNotifications(application: application)
if #available(iOS 13, *) { } else {
app.start()
}
return true
}
// MARK: UISceneSession Lifecycle
#available(iOS 13.0, *)
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
#available(iOS 13.0, *)
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
func applicationDidBecomeActive(_ application: UIApplication) {
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}
}
extension AppDelegate: LocatableOutputProtocol {
func didGetCurrentLocation(latitude: Double, longitude: Double) {
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings) in
if settings.authorizationStatus == .authorized {
let content = UNMutableNotificationContent()
content.title = "\(Date().timeIntervalSince1970)"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "\(Date().timeIntervalSince1970)", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { _ in
}
}
})
}
func failedGetCurrentLocation(error: Error) {
print(error)
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
private func attemptToRegisterForNotifications(application: UIApplication) {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in
if let error = error {
print("failed to get auth", error)
return
}
if granted {
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
} else {
print("NO AVAIL FOR NOTIFS")
}
})
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
}
Also I have an custom LocationManager class:
import CoreLocation
final class LocationManager: NSObject, Locatable {
weak var delegate: LocatableOutputProtocol?
var locationManager: CLLocationManager
override init() {
locationManager = CLLocationManager()
super.init()
let authStatus = CLLocationManager.authorizationStatus()
if CLLocationManager.locationServicesEnabled() {
if (authStatus == .authorizedAlways || authStatus == .authorizedWhenInUse) {
locationManager.delegate = self
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
} else {
locationManager.requestAlwaysAuthorization()
print("we dont have permission")
}
} else {
}
}
func getCurrentLocation() {
locationManager.startUpdatingLocation()
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let coordinates = locations.first?.coordinate {
locationManager.stopUpdatingLocation()
self.delegate?.didGetCurrentLocation(latitude: coordinates.latitude, longitude: coordinates.longitude)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.delegate?.failedGetCurrentLocation(error: error)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("status changed")
if (status == .authorizedAlways || status == .authorizedWhenInUse) {
print("we got permission")
} else {
print("nope")
}
}
}
I am trying to debug this with creating new schema on Xcode with Wait for executable to be launched and using Freeway Ride on Debug menu of Simulator. Also tested with real device.
What am I missing?
#onurgenes, If you add a real code from your project, first of all, how you can start any location updates from here?
if let _ = launchOptions?[.location] {
locationManager = LocationManager()
locationManager?.delegate = self
locationManager?.getCurrentLocation()
return true
}
When app start at for the first time launchOptions will be nil, and your LocationManager() even not started, so your any location monitoring and updates will not work (maybe you have the some code at app.start() but now it looks like an error).
The second thing - at your sample, you are using bought of locating monitoring:
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
so here your location manager handles only significantLocationChanges(). If you want to use both of them - you should toggle it (at didBecomeActiveNotification and didEnterBackgroundNotification) or create different instances of the location manager as Apple recommend.
The third - your problem. Let's look for this part more detailed:
locationManager = LocationManager()
locationManager?.delegate = self
locationManager?.getCurrentLocation()
As I mention up - at LocationManager() you start monitoring location:
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
and this is what you need - significant location changes. But after you call getCurrentLocation() with locationManager.startUpdatingLocation() so you 'rewrite' your monitoring, and that's the reason why you did not get any updates from it.
Also, take in mind:
Significant locations deliver updates only when there has been a
significant change in the device’s location, (experimentally
established 500 meters or more)
Significant locations very inaccurate (for me sometimes it up to 900 meters). Very often significant location use just for wake up an application and restart
location service.
After your app wake up from location changes
notification, you are given a small amount of time (around 10
seconds), so if you need more time to send location to the server
you should request more time with
beginBackgroundTask(withName:expirationHandler:)
Hope my answer was helpful. Happy coding!
#onurgenes You need to use NotificationCenter on your location manager initialize section like below,
import CoreLocation
final class LocationManager: NSObject, Locatable {
weak var delegate: LocatableOutputProtocol?
var locationManager: CLLocationManager
override init() {
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackgroundActive(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForegroundActive(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
locationManager = CLLocationManager()
super.init()
let authStatus = CLLocationManager.authorizationStatus()
if CLLocationManager.locationServicesEnabled() {
if (authStatus == .authorizedAlways || authStatus == .authorizedWhenInUse) {
locationManager.delegate = self
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
} else {
locationManager.requestAlwaysAuthorization()
print("we dont have permission")
}
} else {
}
}
func getCurrentLocation() {
locationManager.startUpdatingLocation()
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let coordinates = locations.first?.coordinate {
locationManager.stopUpdatingLocation()
self.delegate?.didGetCurrentLocation(latitude: coordinates.latitude, longitude: coordinates.longitude)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.delegate?.failedGetCurrentLocation(error: error)
self.locationManager.stopMonitoringSignificantLocationChanges()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("status changed")
if (status == .authorizedAlways || status == .authorizedWhenInUse) {
print("we got permission")
self.locationManager.startMonitoringSignificantLocationChanges()
} else {
print("nope")
}
}
}
#objc private func applicationDidEnterBackgroundActive (_ notification: Notification) {
self.locationManager.startMonitoringSignificantLocationChanges()
}
#objc private func applicationWillEnterForegroundActive (_ notification: Notification) {
self.locationManager.startUpdatingLocation()
}
You need to use this LocationManager class on your AppDelegate class for it's initialize. I hope it will help to achieve your required output.
Related
I tried get the coordinates when user launched app.
I setted up the locationManager code in a independent file:
UserLocation.swift:
import Foundation
import CoreLocation
class UserLocation: NSObject, CLLocationManagerDelegate {
var userCurrentLocation: CLLocationCoordinate2D?
let locationManager = CLLocationManager()
func locationSetup() {
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.authorizedWhenInUse {
print("authorization error")
return
}
locationManager.distanceFilter = 300
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.startUpdatingLocation()
print("startUpdatingLocation")
if CLLocationManager.locationServicesEnabled() {
print("locationServicesEnabled")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("locationManager getting start")
if let location = locations.last {
self.userCurrentLocation = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
print("print location in locationManager: \(String(describing: userCurrentLocation?.latitude))")
locationManager.stopUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didFinishDeferredUpdatesWithError error: Error?) {
print(error?.localizedDescription as Any)
return
}
}
then, I call the func in the AppDelegate.swift's application(_::didFinishLaunchingWithOptions:) like this:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let getUserLocation = UserLocation()
getUserLocation.locationSetup()
}
but , the only calls locationSetup() function successfully , never called the related function locationManager(_::didUpdateLocations:). the print("locationManager getting start") I putted the first line in the locationManager(_::didUpdateLocations:), never printed out
BTW, in the info.plist , I already set Privacy - Location When In Use Usage Description .
can anyone help me out ?
Your getUserLocation is a local variable. It goes out of existence 1 millisecond after you create it. So it never has time to do anything (e.g. location updating). Promote it to an instance variable so that it lives longer:
var getUserLocation : UserLocation?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.getUserLocation = UserLocation()
self.getUserLocation?.locationSetup()
return true
}
(Also please use better variable names. An object reference should not begin with a verb.)
Please cross-check simulator location: Simulator -> Debug -> Locations that shouldn't be None in your case...
Hope this will help you... Thanks :)
I got stuck when trying to keep my function running if I terminate the app.
Is it possible to keep core location (geofencing / geolocating) and core bluetooth running when app is not running ? If possible how to solve my issue? I already check the background modes, and implement core location method.
this is my code :
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var viewController = ViewController()
var window: UIWindow?
var locationManager = CLLocationManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
locationManager = CLLocationManager()
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.pausesLocationUpdatesAutomatically = false
if #available(iOS 9.0, *) {
locationManager.allowsBackgroundLocationUpdates = true
}
beaconRegion.notifyEntryStateOnDisplay = true
beaconRegion.notifyOnEntry = true
beaconRegion.notifyOnExit = true
locationManager.startMonitoring(for: beaconRegion)
locationManager.stopRangingBeacons(in: beaconRegion)
locationManager.startRangingBeacons(in: beaconRegion)
locationManager.startUpdatingLocation()
return true
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if (region.identifier == beaconRegionIdentifier) {
manager.requestState(for: region)
goBackground()
}
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
print("you exited region")
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
if (region.identifier == beaconRegionIdentifier) {
manager.stopUpdatingLocation()
switch state {
case .inside:
manager.startRangingBeacons(in: region as! CLBeaconRegion)
manager.startUpdatingLocation()
case .outside:
let delay = DispatchTime.now() + .seconds(3)
DispatchQueue.main.asyncAfter(deadline: delay) {
manager.requestState(for: region)
}
case .unknown:
let delay = DispatchTime.now() + .seconds(3)
DispatchQueue.main.asyncAfter(deadline: delay) {
manager.requestState(for: region)
}
}
}
}
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
let state = UIApplication.shared.applicationState
switch(state){
case.active,
.inactive,
.background:
let mainView = UserDefaults.standard.bool(forKey: "toMainView")
var isWakeUpRunning = UserDefaults.standard.bool(forKey: "isWakeUpRunning")
if isWakeUpRunning {
if mainView {
for aBeacon in beacons{
if aBeacon.rssi > WAKE_UP_THRESHOLD && aBeacon.rssi != 0{
UserDefaults.standard.set(false, forKey: "isWakeUpRunning")
self.viewController.startFunction()
manager.stopRangingBeacons(in: region)
}else if aBeacon.rssi != 0 && aBeacon.rssi < WAKE_UP_THRESHOLD {
manager.stopRangingBeacons(in: region)
manager.requestState(for: region)
}
}
}
}else{
manager.stopRangingBeacons(in: region)
manager.requestState(for: region)
}
}
}
func goBackground() {
let app = UIApplication.shared
var bgTask: UIBackgroundTaskIdentifier = 0
bgTask = app.beginBackgroundTask(expirationHandler: {
NSLog("Expired: %lu", bgTask)
app.endBackgroundTask(bgTask)
})
NSLog("Background: %lu", bgTask)
}
}
From my code, it can run in both in foreground and background. but when i swipe up the app from task switcher, it cannot work. and i cannot see the log too from xcode. Any ideas to help me ?
Once you swipe up the app from the task switcher your app will be killed, but CoreLocation will still be working for you at the OS level, looking for beacons that match your region:
locationManager.startMonitoring(for: beaconRegion)
Once there is a change on that region (either a didEnter or a didExit), then your app will be re-launched into the background. At this time the following methods will be called in order:
application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)
locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion)
At that time your app will continue running in the background. Because your app starts a background task, this will continue for 180 seconds before being suspended.
However, your app will not run between the time it is swiped off the screen and when the next region transition happens. This is the best you can do.
I want to get new location every 1min when my app is in background or killed.
Here is my code :
Location Service:
class LocationService: NSObject, CLLocationManagerDelegate {
static let shared = LocationService()
var locationManager = CLLocationManager()
var significatLocationManager = CLLocationManager()
var currentLocation: CLLocation!
var timer = Timer()
var bgTask = UIBackgroundTaskInvalid
func startUpdatingLocation() {
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
if #available(iOS 9.0, *) {
locationManager.allowsBackgroundLocationUpdates = true
}
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
func stopUpdatingLocation() {
locationManager.stopUpdatingLocation()
timer.invalidate()
}
func restartUpdatingLocation() {
locationManager.stopMonitoringSignificantLocationChanges()
timer.invalidate()
startUpdatingLocation()
}
func startMonitoringLocation() {
locationManager.stopUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
timer.invalidate()
}
func changeLocationAccuracy(){
switch locationManager.desiredAccuracy {
case kCLLocationAccuracyBest:
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManager.distanceFilter = 99999
case kCLLocationAccuracyThreeKilometers:
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
default: break
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(self.bgTask)
self.bgTask = UIBackgroundTaskInvalid
})
currentLocation = locations.last!
let interval = currentLocation.timestamp.timeIntervalSinceNow
let accuracy = self.locationManager.desiredAccuracy
if abs(interval) < 60 && accuracy != kCLLocationAccuracyThreeKilometers {
timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(LocationService.changeLocationAccuracy), userInfo: nil, repeats: false)
changeLocationAccuracy()
}
}
}
App delegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if launchOptions?[UIApplicationLaunchOptionsKey.location] != nil {
LocationService.shared.restartUpdatingLocation()
}
}
func applicationDidEnterBackground(_ application: UIApplication) {
LocationService.shared.restartUpdatingLocation()
}
func applicationWillTerminate(_ application: UIApplication) {
LocationService.shared.startMonitoringLocation()
}
View controller:
override func viewDidLoad() {
LocationService.shared.startUpdatingLocation()
}
But my code is not working, i'm not getting new location after a few minutes when my app is in background. and same when my app is suspended or killed.
Is there any solution for that ? please not that i'm using Swift 3 & xcode 8.1.
Thank's in advance
If you call startUpdatingLocation when your app is already in the background, then you will only receive location updates for a few minutes.
If you call startUpdatingLocation while your app is in the foreground and then your app moves to the background, you will continue to receive location updates indefinitely.
If you call startMonitoringSignificantLocationChanges in the foreground and leave it enabled then you can call startUpdatingLocation in the background and receive updates indefinitely.
If the user terminates your app (by swiping up in the app switcher) then you will no longer receive location updates until the user re-launches your app.
Since your code stops and starts location monitoring when it moves to the background of only get location updates for a few minutes. If you start location monitoring foreground and do nothing when the app moves to the background then you will continue to receive location updates.
Hi am developing a app using swift i want to fetch current location of the user when app launches so i written my code in app delegate i have include all the functions and methods i.e.. added and imported frameworks core location and also updated plist but i cant able to fetch current location
code in my app delegate:
import UIKit
import CoreLocation
import MapKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,GIDSignInDelegate,CLLocationManagerDelegate {
var locationManager:CLLocationManager!
var window: UIWindow?
var centerContainer: MMDrawerController?
private var currentCoordinate: CLLocationCoordinate2D?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
IQKeyboardManager.sharedManager().enable = true
self.locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
determineMyCurrentLocation()
var configureError: NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
if (configureError != nil){
print("We have an error:\(configureError)")
}
GIDSignIn.sharedInstance().clientID = "331294109111-o54tgj4kf824pbb1q6f4tvfq215is0lt.apps.googleusercontent.com"
GIDSignIn.sharedInstance().delegate = self
return true
}
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.locationManager.stopUpdatingLocation()
let latestLocation = locations.last
let latitude = String(format: "%.4f", latestLocation!.coordinate.latitude)
let longitude = String(format: "%.4f", latestLocation!.coordinate.longitude)
print("Latitude: \(latitude)")
print("Longitude: \(longitude)")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Error \(error)")
}
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
if (error == nil){
// let googleName = user.profile.name
let locValue : CLLocationCoordinate2D = currentCoordinate!
let latitude = locValue.latitude
let longitude = locValue.longitude
let userID = UIDevice.currentDevice().identifierForVendor!.UUIDString
print("users id = \(userID)")
print("userlatitude = \(latitude)")
print("userlongitude\(longitude)")
print(user.userID)
let profilePicURL = user.profile.imageURLWithDimension(200).absoluteString
print(profilePicURL)
let mainstoryboard = UIStoryboard(name: "Main", bundle:nil)
let centerViewController = mainstoryboard.instantiateViewControllerWithIdentifier("FourthViewController") as! FourthViewController
centerViewController.userid = socialMessage as String
let leftViewController = mainstoryboard.instantiateViewControllerWithIdentifier("LeftSideViewController") as! LeftSideViewController
leftViewController.ProName = user.profile.name
leftViewController.proImage = profilePicURL as String
let leftSideNav = UINavigationController(rootViewController: leftViewController)
let centerNav = UINavigationController(rootViewController: centerViewController)
self.centerContainer = MMDrawerController(centerViewController: centerNav, leftDrawerViewController: leftSideNav)
self.centerContainer!.openDrawerGestureModeMask = MMOpenDrawerGestureMode.PanningCenterView;
self.centerContainer!.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.PanningCenterView;
self.window!.rootViewController = self.centerContainer
self.window!.makeKeyAndVisible()
}
}
else{
print("looks we got signin error:\(error)")
}
}
func application(application: UIApplication,
openURL url: NSURL, options: [String: AnyObject]) -> Bool {
return GIDSignIn.sharedInstance().handleURL(url,
sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return GIDSignIn.sharedInstance().handleURL(url, sourceApplication: sourceApplication, annotation: annotation)
}
func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!,
withError error: NSError!) {
// Perform any operations when the user disconnects from app here.
// ...
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
And also i want to use current lat and long in the method:
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
here i want to use lat and long
}
// Just call setupLocationManager() in didFinishLaunchingWithOption.
func setupLocationManager(){
locationManager = CLLocationManager()
locationManager?.delegate = self
self.locationManager?.requestAlwaysAuthorization()
locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager?.startUpdatingLocation()
}
// Below method will provide you current location.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if currentLocation == nil {
currentLocation = locations.last
locationManager?.stopMonitoringSignificantLocationChanges()
let locationValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locationValue)")
locationManager?.stopUpdatingLocation()
}
}
// Below Mehtod will print error if not able to update location.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error")
}
By the following code you can get name of location and it's longitude and latitude
extension AppDelegate : CLLocationManagerDelegate
{
func geocode(latitude: Double, longitude: Double, completion: #escaping (CLPlacemark?, Error?) -> ()) {
CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { completion($0?.first, $1) }
}
// Below Mehtod will print error if not able to update location.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error Location")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//Access the last object from locations to get perfect current location
if let location = locations.last {
let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)
geocode(latitude: myLocation.latitude, longitude: myLocation.longitude) { placemark, error in
guard let placemark = placemark, error == nil else { return }
// you should always update your UI in the main thread
DispatchQueue.main.async {
// update UI here
print("address1:", placemark.thoroughfare ?? "")
print("address2:", placemark.subThoroughfare ?? "")
print("city:", placemark.locality ?? "")
print("state:", placemark.administrativeArea ?? "")
print("zip code:", placemark.postalCode ?? "")
print("country:", placemark.country ?? "")
}
}
}
manager.stopUpdatingLocation()
}
}
Does anyone know if an app can get notified in the background by the system when app permissions change? I'm especially interested in getting notified when a user changes the "location" permission and the "background app refresh" permission.
So far I have looked into this call-back method:
locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus)
However, the app doesn't get notified in the background.
I also tried adding an observer for this notification:
UIApplicationBackgroundRefreshStatusDidChangeNotification
But I can't get it to work either.
Here's my code:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "checkBackgroundPermission", name: UIApplicationBackgroundRefreshStatusDidChangeNotification, object: nil)
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.pausesLocationUpdatesAutomatically = false
if(locationManager.respondsToSelector("requestAlwaysAuthorization")) {
locationManager.requestAlwaysAuthorization()
}
if launchOptions?[UIApplicationLaunchOptionsLocationKey] != nil {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.pausesLocationUpdatesAutomatically = false
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let uuidString = prefs.stringForKey("UUID") as String!
let uuid : NSUUID? = NSUUID(UUIDString: uuidString as String)
beaconRegionGeneral = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: uuidString), identifier: "general")
locationManager.startRangingBeaconsInRegion(beaconRegionGeneral)
setIsRanging(true)
}
if(application.respondsToSelector("registerUserNotificationSettings:")) {
application.registerUserNotificationSettings(
UIUserNotificationSettings(
forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Sound,
categories: nil
)
)
}
return true
}
func checkBackgroundPermission() {
sendLocalNotificationWithMessage("checkBackgroundPermission", playSound: false)
println("checkBackgroundPermission")
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
sendLocalNotificationWithMessage("didChangeAuthorizationStatus", playSound: true)
println("didChangeAuthorizationStatus")
}
you can use below delegate method (from CLLocationManagerDelegate Protocol) to get notifications.
optional func locationManager(_ manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus)