How to fetch current location in appdelegate using swift - ios

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()
}
}

Related

Can not called locationManager(_::didUpdateLocations:)

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 :)

Background Location Updates

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.

Detect iBeacon when app is killed swift

I need to do something if iPhone detect (beacon in background) with UUID: "3E06945C-F54A-4BE4-ABB2-79764DA6AC6F" so I am trying to do this, in AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
application.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert], categories: nil))
initBeaconManager()
//Fabric.with([Crashlytics.self])
//Fabric.with([Appsee.self])
return true
}
func applicationWillTerminate(_ application: UIApplication) {
print("Application will terminate")
}
func applicationDidEnterBackground(_ application: UIApplication) {
isInForeground = false
isInBackground = true
extendBackgroundTime()
}
func applicationDidBecomeActive(_ application: UIApplication) {
isInForeground = true
isInBackground = false
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "initCarPlaceNotification"), object: nil)
}
func extendBackgroundTime() {
if backgroundTask != UIBackgroundTaskInvalid {
// Still running
return
}
else {
backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "Ranging", expirationHandler: { () in
// Background task expired by iOS
UIApplication.shared.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
});
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { //
if !self.isInForeground {
while true {
Thread.sleep(forTimeInterval: 1)
}
}
}
}
func initBeaconManager() {
let beaconsUUIDs = ["1":"3E06945C-F54A-4BE4-ABB2-79764DA6AC6F"]
locationManager = CLLocationManager()
if (locationManager!.responds(to: #selector(CLLocationManager.requestAlwaysAuthorization))) {
locationManager!.requestWhenInUseAuthorization()
}
locationManager!.delegate = self
locationManager!.pausesLocationUpdatesAutomatically = true
for (key, value) in beaconsUUIDs {
let beaconUUID:UUID = UUID(uuidString: value)!
let beaconRegion = CLBeaconRegion(proximityUUID: beaconUUID, identifier: "reg-\(key)")
locationManager!.startMonitoring(for: beaconRegion)
locationManager!.startRangingBeacons(in: beaconRegion)
}
locationManager!.startUpdatingHeading()
locationManager!.startUpdatingLocation()
}
extension AppDelegate {
func rangeForAllBeacons(_ beacons:[CLBeacon]) {
if beacons[0].proximityUUID == UUID(uuidString: "3E06945C-F54A-4BE4-ABB2-79764DA6AC6F") {
displayNotification("work fine..")
}
}
extension AppDelegate:CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
if !isInForeground {
extendBackgroundTime()
}
print(beacons)
for beacon in beacons {
if beacon.rssi < -20 {
nearbyBeacons.append(beacon)
}
}
if firstRegionDetected == "" {
firstRegionDetected = region.identifier
} else if firstRegionDetected == region.identifier {
rangeForAllBeacons(nearbyBeacons)
nearbyBeacons = []
}
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
if isInBackground {
extendBackgroundTime()
}
}
But it doesn't work. On the info.plist I use
Privacy - Location Always Usage Description
and
Privacy - Location When In Use Usage Description

How to keep Core Location and Core Bluetooth running when app is not running (killed/ terminated)?

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.

iOS: Notifications and iBeacon

I have an app that needs to send notifications when user is out of range of iBeacon. The problem is that user becomes notifications randomly: sometimes it works, sometimes it doesn't work.
My code:
// this function I call in viewDidLoad for my UIViewController
func startMonitorig() {
let beaconRegion:CLBeaconRegion = {
let r = CLBeaconRegion(proximityUUID: UUID(uuidString: "XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")!, major: 1, minor: 6, identifier: "com.myapp.identifier")
return r
}()
locationManager.startMonitoring(for: beaconRegion)
locationManager.startRangingBeacons(in: beaconRegion)
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
startMonitorig()
}
AppDelegate:
let locationManager = CLLocationManager()
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Request permission to send notifications
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.alert, .sound]) { (granted, error) in }
locationManager.delegate = self
return true
}
extension AppDelegate: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
guard region is CLBeaconRegion else { return }
let content = UNMutableNotificationContent()
content.title = "Forget Me Not"
content.body = "Are you forgetting something?"
content.sound = .default()
let request = UNNotificationRequest(identifier: "ForgetMeNot", content: content, trigger: nil)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}
I'm curious why it's like that and what I'm doing wrong? What can be the reason?

Resources