Why does the confirmation window disappear in viewDidLoad? - swift

Trying to get the user's location. A confirmation window appears for 1 second and immediately disappears
import UIKit
import MapKit
import CoreLocation
class NearbyViewController: UIViewController, CLLocationManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
}
}

Make
let locationManager = CLLocationManager()
instance variable
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()
}
}
as it's get deallocated end of viewDidLoad which hides the alert automatically

Probably because the locationManager is getting deallocated when viewDidLoad completes.
Also, I would consider possibly moving to viewWillAppear or viewDidAppear.
Try this:
import UIKit
import MapKit
import CoreLocation
class NearbyViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()
}
}
Or this:
import UIKit
import MapKit
import CoreLocation
class NearbyViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
locationManager.requestWhenInUseAuthorization()
}
}

Related

Why my didUpdate userLocation method doesn't get called?

I have a MapKit in my view, and I want to access the userLocation data. However, the actual function
func firstMapView(_ firstMapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
print("it never gets called")
}
never ends up being called.
The whole code looks like this:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate{
#IBOutlet weak var firstMapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
firstMapView.delegate = self
}
func firstMapView(_ firstMapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
print("it never gets called")
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
print("Authorized when in use detected")
locationManager.startUpdatingLocation()
firstMapView.showsUserLocation = true
}
}
}
When I run the code I get the debug message: print("Authorized when in use detected")
I saw this question, and tried to copy the things, but it didn't help.
Use this delegate function
func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
print(userLocation)
}
delete this one
func firstMapView(_ firstMapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
print("it never gets called")
}

Why can I access iPhone's location without "import CoreLocation"?

I am able to access a device's location with the following code. I am using MapKit instead of CoreLocation. I thought this instance CLLocationManager() and method requestAlwaysAuthorization() were only available through the CoreLocation framework?
import UIKit
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
locationManager.delegate = self
self.locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for currentlocation in locations{
print("\(index): \(currentlocation)")
}
}
}
MapKit imports CoreLocation so you don't need to. Just like you don't need to import Foundation because you get that from UIKit.

Show custom location with pin on Map with MapKit (Swift)

I am trying to create a view for in my app which shows the location of a restaurant. When the user enters the view, it shows something like this
But instead shows the location of the restaurant with a pin and a more zoomed in view. I am new to MapKit and have not been able to make any progress.
This is what my view consists of.
And this is what my view controller consists of.
import UIKit
import MapKit
class FD1ViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView!
private let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import UIKit
import MapKit
class FD1ViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//Create the pin location of your restaurant(you need the GPS coordinates for this)
let restaurantLocation = CLLocationCoordinate2D(latitude: 111.0, longitude: 111.0)
//Center the map on the place location
mapView.setCenter(restaurantLocation, animated: true)
}
}
This should do it. I hope it helps!

I can't add current location to Google Maps

import UIKit
import GoogleMaps
import CoreLocation
class ViewController: UIViewController {
let locationManager = CLLocationManager()
var mapView: GMSMapView?
override func viewDidLoad() {
super.viewDidLoad()
GMSServices.provideAPIKey("XYZ")
let camera = GMSCameraPosition.cameraWithLatitude(37.621262,longitude: -122.378945, zoom: 12)
mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
view = mapView
}
}
What should I add to this code?
This should help you,Please check.
import UIKit
import GoogleMaps
import CoreLocation
class ViewController: UIViewController {
let locationManager = CLLocationManager()
var mapView: GMSMapView?
override func viewDidLoad()
{
super.viewDidLoad()
GMSServices.provideAPIKey("XYZ")
let camera = GMSCameraPosition.camera(withLatitude: 37.621262,longitude: -122.378945, zoom: 12)
mapView = GMSMapView.map(withFrame: CGRect.init(), camera: camera)
// Below line is to default show user current location(Bue dot with circular accuracy radius around it)
mapView!.isMyLocationEnabled = true
view = mapView
}
}
Hope that helps.

Swift, CLLocationManagerDelegate in NSObject not working

i have problem with getting my location with CLLocationDelegate.
i created new subclass of UIView and work well, but when i created subclass of NSObject, CLLocationDelegate not called. I can find where is problem.
here is my code:
import UIKit
import CoreLocation
class LocationData: NSObject, CLLocationManagerDelegate {
var locationManager : CLLocationManager = CLLocationManager()
override init() {
super.init()
if self.locationManager.respondsToSelector(Selector("requestAlwaysAuthorization")) {
self.locationManager.requestWhenInUseAuthorization()
}
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = 50
self.locationManager.startUpdatingLocation()
println("init LocationData")
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println(error.description)
}
func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
println("updated")
}
}
Thanks!
Your code is fine! But when instantiating the class, you need to do like this:
import UIKit
class ViewController: UIViewController {
let LocationData: LocationData = LocationData() //<- here is the secret to works!!!
override func viewDidLoad() {
super.viewDidLoad()
}
I also suggest that you change your init to something like this:
override init() {
super.init()
let authorizationStatus: CLAuthorizationStatus = CLLocationManager.authorizationStatus()
if authorizationStatus == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = 50
self.locationManager.startUpdatingLocation()
print("init LocationData")
}
And don't forget to add NSLocationWhenInUseUsageDescription in the info.plist project.