How to get Location (latitude & longitude value) in variable on iOS?

后端 未结 3 1850
南旧
南旧 2020-12-15 07:41

I would like to use the location of my app user, more specifically the latitude and longitude value.

I need them to use in a variable, so that I can send them with

3条回答
  •  离开以前
    2020-12-15 08:18

    STEP 1 : Add CoreLocation framework in your project.

    1. Select TARGETS -> Build Phases
    2. Select Link Binary With Libraries
    3. Click on plus (+) button. This will pop-up framework list.
    4. Search CoreLocation framework and Add it.

    Screenshot 1

    Screenshot 2

    STEP 2 : Write below code in header file of view controller where location is to be fetched :

    #import 
    

    Also, add CLLocationManagerDelegate in interface.

    Now, create object of LocationManager

     CLLocationManager *locationManager;
    

    STEP 3 : In, ViewDidLoad method write below code :

        locationManager = [[CLLocationManager alloc] init];
        locationManager.distanceFilter = kCLDistanceFilterNone;
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        [locationManager startUpdatingLocation];
    
        [locationManager requestAlwaysAuthorization]; //Note this one
    

    You can set desiredAccuracy value as kCLLocationAccuracyBest, kCLLocationAccuracyNearestTenMeters, kCLLocationAccuracyHundredMeters, kCLLocationAccuracyKilometer, kCLLocationAccuracyThreeKilometers

    Now, write below code to get latitude and longitude value

        float Lat = locationManager.location.coordinate.latitude;
        float Long = locationManager.location.coordinate.longitude;
        NSLog(@"Lat : %f  Long : %f",Lat,Long);
    

    STEP 4 : In iOS 8, this code fails silently i.e you won’t get any error or warning.

    You need to do two extra things to get location working:

    1. Add a key to your Info.plist
    2. Request authorization from the location manager asking it to start.

    Any one or both of below keys needs to be added in Info.plist file.

    1. NSLocationWhenInUseUsageDescription
    2. NSLocationAlwaysUsageDescription

    These are of String type and value can be any message description or empty.

    Now you need to request authorisation for corresponding location method. Use any one of below calls :

    1. [self.locationManager requestWhenInUseAuthorization]
    2. [self.locationManager requestAlwaysAuthorization]

提交回复
热议问题