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?
Related
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.
My notification works fine on simulator but on my device (running iOS 10.3.3) the notification does not show at all (phone locked at time of trigger) but the phone does vibrate when triggered and the app does get updated to correct settings so I know that the notification is getting triggered - its just not visually showing on the device. Have I missed anything?
This is where I setup authorisation for notifications in AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
locationManager.delegate = self
// Setup notifications authorization request
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Check if granted, if not then notify user
if granted {
print("Notification access granted")
} else {
print(error?.localizedDescription ?? "General Error: notification access not granted")
self.window?.rootViewController?.showAlertApplicationSettings(forErorType: .turnOnNotifications)
}
}
Location trigger in AppDelegate:
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if region is CLCircularRegion {
print("DidEnter: \(region.identifier)")
handleEvent(forRegion: region)
}
}
Handle event code that gets data from core data and then send to notifyUser method in AppDelegate:
func handleEvent(forRegion region: CLRegion) {
guard let reminder = getReminder(fromRegionIdentifier: region.identifier) else {
// There was a problem access the notification data, inform user
notifyUser(title: "Reminder notifiction error", subtitle: "One of your notifications has just been triggered but error restriving notification data", notes: nil)
return
}
notifyUser(title: reminder.titleString, subtitle: "Reminder has been triggered", notes: reminder.notesString)
updateRemindersState(reminder: reminder)
}
This is the actual notification trigger code in AppDelegate:
func notifyUser(title: String, subtitle: String, notes: String?) {
// show an alert if applocation is active
if UIApplication.shared.applicationState == .active {
window?.rootViewController?.showAlert(title: title, message: subtitle)
} else {
let notification = UNMutableNotificationContent()
notification.title = title
notification.subtitle = subtitle
if let notes = notes {
notification.body = notes
}
notification.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: "Notification", content: notification, trigger: nil)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
if let error = error {
print(error)
}
})
}
}
p.s. checked that on my device in settings its has Show in Notifications Centre, sounds, show on lock screen, banners all turned on.
i am new in estimote beacon programming .i want to detect the estimote beacon when app is closed. And when beacon is detected then fire the particular notification. how i can done it?
give me suggestions please. i had done the following code. but i can not getting any notification
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
beaconManager.delegate = self
beaconManager.startMonitoring(for: region)
beaconManager.startRangingBeacons(in: region)
}
func beaconManager(_ manager: Any, didEnter region: CLBeaconRegion) {
NSLog("beaconManager : didEnter Called")
let content = UNMutableNotificationContent()
content.title = "Beacon Detected"
content.body = "Enter region"
content.sound = UNNotificationSound.default()
let trigger = UNLocationNotificationTrigger(region:region, repeats:false)
let request = UNNotificationRequest(identifier: "Enter region", content: content, trigger: trigger)
center.add(request) { (error) in
if let error = error {
print(error.localizedDescription)
}
}
}
func beaconManager(_ manager: Any, didExitRegion region: CLBeaconRegion) {
NSLog("beaconManager : didExitRegion Called")
let content = UNMutableNotificationContent()
content.title = "Beacon Detected"
content.body = "Exit region"
content.sound = UNNotificationSound.default()
let trigger = UNLocationNotificationTrigger(region:region, repeats:false)
let request = UNNotificationRequest(identifier: "Enter region", content: content, trigger: trigger)
center.add(request) { (error) in
if let error = error {
print(error.localizedDescription)
}
}
}
In app delegate write the desired code under estimate delegate methods. Sample code as follows,
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
if launchOptions["UIApplicationLaunchOptionsLocationKey"] != nil {
beaconManager = ESTBeaconManager()
beaconManager.delegate = self
// don't forget the NSLocationAlwaysUsageDescription in your Info.plist
beaconManager.requestAlwaysAuthorization()
beaconManager.startMonitoring(for: ESTBeaconRegion(proximityUUID: ESTIMOTE_PROXIMITY_UUID, identifier: "AppRegion"))
}
return true
}
func beaconManager(_ manager: ESTBeaconManager, didEnter region: ESTBeaconRegion) {
let notification = UILocalNotification()
notification.alertBody = "Enter region"
notification.soundName = UILocalNotificationDefaultSoundName as? String
UIApplication.shared.presentLocalNotificationNow(notification)
}
func beaconManager(_ manager: ESTBeaconManager, didExitRegion region: ESTBeaconRegion) {
let notification = UILocalNotification()
notification.alertBody = "Exit region"
notification.soundName = UILocalNotificationDefaultSoundName as? String
UIApplication.shared.presentLocalNotificationNow(notification)
}
This is old code, may have few changes. Follow estimate community's thread for more information. You can find your problem on this thread https://community.estimote.com/hc/en-us/articles/203253193-Pushing-notifications-from-iBeacon-when-the-app-is-in-the-background-or-killed
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
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()
}
}