Request Location Swift iOS 9 - ios

I am trying to get my app to request the user to allow location services when using the app,
I have imported the following in my ViewController.swift
import CoreData
import Foundation
import CoreLocation
and also have the following code in my ViewController.swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let manager = CLLocationManager()
if CLLocationManager.locationServicesEnabled() {
manager.startUpdatingLocation()
}
if CLLocationManager.authorizationStatus() == .NotDetermined {
manager.requestWhenInUseAuthorization()
}
in addition after doing a bunch of research I found that I had to add the following to my info.plist
<key>NSLocationUsageDescription</key>
<string>AppName needs to use your location to help you find other blah blah blah near you</string>
Despite taking these steps when running the app in the simulator I don't get a prompt requesting access when using the app

Insert below key in your Info.plist
NSLocationWhenInUseUsageDescription

Related

Im having a trouble to add locationManager.requestWhenInUseAuthorization()

Im having a trouble to add locationManager.requestWhenInUseAuthorization()
What i expect : popup asking for location permission to user
What heppend : nothing show
Setting : location setting in iphone : never
Plist:
LocationAlwaysAndWhenInuseUsageDescription
LocationAlwaysUsageDescription
LocationWhenInUseUsageDescription
import Foundation
import UIKit
import CoreLocation
class NoobNoobVC: BaseVC, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.distanceFilter = 5
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
//locationManager.startUpdatingHeading()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
locationManager.requestWhenInUseAuthorization()
}
}
Documentation says:
You may call requestWhenInUseAuthorization() whenever the current authorization status is not determined (CLAuthorizationStatus.notDetermined).
&
If the initial authorization status is anything other than CLAuthorizationStatus.notDetermined, this method does nothing and doesn't call the locationManager(_:didChangeAuthorization:) method.
You have to use authorizationStatus() to check the authorization status and then take a proper action like - inform the user what's wrong, ... and what can be done about it. You can call requestWhenInUseAuthorization() only if it's .notDetermined. This class function is marked as deprecated and if you're targeting iOS >= 14.0 you should use the instance variant.

AWS DynamoDB Object Mapper crashing with SIGABRT

I'm trying to build an iPhone app with swift, I've installed all the dependencies on "connect to your back-end" https://docs.aws.amazon.com/aws-mobile/latest/developerguide/add-aws-mobile-nosql-database.html , I even have the amazon aws login page so it's def connected, just whenenver I add this line:
let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default()
that it tells me to do in the tutorial, the app crashes on the screen that code is associated to with Thread 1: SIGABRT. Here's my code on the screen it's on.
import UIKit
import MapKit
import AWSCore
import AWSAuthUI
import AWSMobileClient
import AWSUserPoolsSignIn
import AWSDynamoDB
class SampleViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default()
if !AWSSignInManager.sharedInstance().isLoggedIn {
presentAuthUIViewController()
self.navigationController?.isNavigationBarHidden = true
}
}
#IBAction func askPermission(_ sender: UIButton) {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func presentAuthUIViewController() {
let config = AWSAuthUIConfiguration()
config.enableUserPoolsUI = true
AWSAuthUIViewController.presentViewController(
with: self.navigationController!,
configuration: config, completionHandler: { (provider: AWSSignInProvider, error: Error?) in
if error == nil {
// SignIn succeeded.
} else {
// end user faced error while loggin in, take any required action here.
}
})
}
}
I'd appreciate any help, and can post more information if needed. Thank you so much.
Can you add the following to the awsconfiguration.json after the section that defines "DynamoDBObjectMapper". Replace the 'YourRegion' placeholder below with the region where your Database is located. This is a required section in the awsconfiguration.json file and there may be in a bug in the tool that generates the config.
"DynamoDB": {
"Default": {
"Region": "YourRegion"
}
},

Google places API doesn't work as expected

I am following Google Places API for IOS tutorial to view the user current place.
I used the same code in the tutorial as follow:
var placesClient: GMSPlacesClient!
// Add a pair of UILabels in Interface Builder, and connect the outlets to these variables.
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var addressLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
placesClient = GMSPlacesClient.shared()
}
// Add a UIButton in Interface Builder, and connect the action to this function.
#IBAction func getCurrentPlace(_ sender: UIButton) {
placesClient.currentPlace(callback: { (placeLikelihoodList, error) -> Void in
if let error = error {
print("Pick Place error: \(error.localizedDescription)")
return
}
self.nameLabel.text = "No current place"
self.addressLabel.text = ""
if let placeLikelihoodList = placeLikelihoodList {
let place = placeLikelihoodList.likelihoods.first?.place
if let place = place {
self.nameLabel.text = place.name
self.addressLabel.text = place.formattedAddress?.components(separatedBy: ", ")
.joined(separator: "\n")
}
}
})
}
But I get the following error in the console:
Pick Place error: The operation couldn’t be completed. The Places API
could not find the user's location. This may be because the user has
not allowed the application to access location information.
NOTE: I have set the NSLocationWhenInUseUsageDescription key (Privacy - Location When In Use Usage Description) in info.plist file.
It's confusing because I followed the tutorial step by step. And am testing the application using physical device with "Locations Services" enabled .
Any idea what I might be doing wrong?
Or is it because the documentation is not up-to-date?
This may be because the user has not allowed the application to access location information.
This points you towards your answer. For Google Places to work you need to request to use location services by calling requestWhenInUseAuthorization(). This will prompts the user to grant permission to the app to use location services.
Please refer to the Apple Docs for more info.
EDIT
You should keep a strong reference to the CLLocationManager that you create so it does not get deallocated when your function exits.
"Create an instance of the CLLocationManager class and store a strong reference to it somewhere in your app.
Keeping a strong reference to the location manager object is required until all tasks involving that object are complete. Because most location manager tasks run asynchronously, storing your location manager in a local variable is insufficient."
Taken from the CLLocationManager Docs
EXAMPLE
class LocationViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad()
{
super.viewDidLoad()
locationManager.delegate = self
if CLLocationManager.authorizationStatus() == .notDetermined
{
locationManager.requestWhenInUseAuthorization()
}
}
}
1. Request user for Location Usage Authorization
requestWhenInUseAuthorization() OR requestAlwaysAuthorization() according to your requirement.
2. In Info.plist, add the following keys:
a. NSLocationAlwaysUsageDescription OR NSLocationWhenInUseUsageDescription
b. NSLocationAlwaysAndWhenInUseUsageDescription
Example:
class ViewController: UIViewController, CLLocationManagerDelegate
{
let locationManager = CLLocationManager()
override func viewDidLoad()
{
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus)
{
}
}

Swift: Utilizing CLLocationManagerDelegate and CoreLocation.framework results in "Use of undeclared type" error

I'm going off a youtube video that gives a basic example of utilizing the location services of Xcode to program a sort of maps user interface to a program. I followed the steps in the video of setting up the program and get an assumedly simple "Use of undeclared type" error when trying to compile the application.
https://www.youtube.com/watch?v=qrdIL44T6FQ - Link to the youtube video.
The problem occurs at the class creation line.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate
{ // ^ Use of undeclared type
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreate-d.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordingate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
self.location.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, difFailWithError error: NSError)
{
print("Errors: " + error.localizedDescription)
}
}
I'm not sure why the error is occurring.
I added the CoreLocation.framework in the "Link Binary With Libraries" section. I made sure to add the "NSLocationWhenInUseUsageDescription" to the Info.plist.
I connected the Map View Kit to the code itself at 2:26 in the video.
Other ways to go about doing this is also of interest. I'm solely trying to get a basic location services clearance to run in a program.
Version: Xcode Version 7.3.1
In swift
I was missing importing CoreLocation. I have added following line on top of my file and it worked.
import CoreLocation
I made a new project and followed the steps in the video again and the project now works appropriately. The only thing that may have caused the issue was I checked off Core Data when creating the project. I do not believe this is exactly why it was throwing an error, but if you run into a similar situation make sure this box is left empty.

parse geoPointForCurrentLocationInBackground Swift sample

Found multiple posts on this, but still can't quite piece it together.
I'm using Parse to retrieve the user's current location. Documentation makes it seem very easy, but several things appear to be missing. https://parse.com/docs/ios/guide#geopoints-getting-the-user-39-s-current-location
First, my code:
class TableViewController: UITableViewController, CLLocationManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
print("Get GPS")
PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint, error ) -> Void in
if error == nil {
print("Got geoPoint") //Never reaches this
print(geoPoint)
} else {
print(error ) //No error either
}
}
I've updated the NSLocationWhenInUseUsageDescription in my info.plist
Tried simulator and two real devices.
Added CLLocationManagerDelegate
I'm trying to avoid making this more complex than it needs to be.
I've also experimented with CLLocationManager samples and it doesn't seem to be working either.
I'm using most recent versions of everything... started with Parse yesterday!
I've never been challenged for authorization to use my location. Tried that with CLLocationManager examples!
Would greatly appreciate some guidance / support.
You are right about missing a few things before you can handle the location update from Parse.
First, add a location manager property to your class.
class TableViewController: UITableViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
Set its delegate and use it to request authorization from the user:
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
print("Get GPS")
PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint, error ) -> Void in
if error == nil {
print("Got geoPoint") //Never reaches this
print(geoPoint)
} else {
print(error ) //No error either
}
}
}
In your Info.plist, you need to add a key NSLocationWhenInUseUsageDescription and give it a string value for a message to the user during the authorization request.
The authorization request and the location update should work after the above changes.

Resources