Bagaimana saya bisa mendapatkan lokasi saat ini dari pengguna di iOS

Jawaban:

336

Jawaban RedBlueThing bekerja cukup baik untuk saya. Berikut adalah beberapa contoh kode tentang bagaimana saya melakukannya.

Header

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface yourController : UIViewController <CLLocationManagerDelegate> {
    CLLocationManager *locationManager;
}

@end

MainFile

Dalam metode init

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];

Fungsi panggilan balik

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
    NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}

iOS 6

Di iOS 6 fungsi delegasi tidak digunakan lagi. Delegasi baru adalah

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

Karenanya untuk mendapatkan posisi baru gunakan

[locations lastObject]

iOS 8

Di iOS 8 izin harus ditanyakan secara eksplisit sebelum mulai memperbarui lokasi

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    [self.locationManager requestWhenInUseAuthorization];

[locationManager startUpdatingLocation];

Anda juga harus menambahkan string untuk NSLocationAlwaysUsageDescriptionatau NSLocationWhenInUseUsageDescriptionkunci ke Info.plist aplikasi. Kalau tidak, panggilan ke startUpdatingLocationakan diabaikan dan delegasi Anda tidak akan menerima panggilan balik.

Dan pada akhirnya ketika Anda selesai membaca panggilan lokasi berhenti memperbarui lokasi di tempat yang sesuai.

[locationManager stopUpdatingLocation];
dplusm
sumber
4
+1 terima kasih telah mengirim potongan kode sederhana untuk memuji jawaban yang diterima
AngeloS
12
Hati-hati dengan contoh ini, nilai properti ini mengarah pada konsumsi baterai yang lebih tinggi.
DanSkeel
36
PENTING: Anda juga perlu "stopUpdatingLocations" jika tidak metode delegasi akan dipanggil setiap kali pengguna mengubah lokasinya. Demikian masalah baterai yang disebutkan di atas dan juga jika ada metode lain yang dipicu dalam metode delegasi ini, itu akan terus dipanggil. Selamat Coding Guys !! Bersulang!!
Apple_iOS0304
5
Anda adalah tipe pengguna yang membuat StackOverflow hebat. Cuplikan kode patut dicontoh dan saya harap lebih banyak orang menyertakan mereka dengan jawaban mereka.
Danny
26
Untuk iOS 8.0+ Anda harus memasukkan kunci berikut di Info.plist proyek Anda: NSLocationAlwaysUsageDescriptionjika Anda menggunakan [self.locationManager requestAlwaysAuthorization]atau NSLocationWhenInUseUsageDescriptionjika Anda menggunakan [self.locationManager requestWhenInUseAuthorization]. Juga untuk mendukung iOS 6.0+ ke iOS 7.0+ termasuk kunci NSLocationUsageDescriptionatau 'Privasi - Deskripsi Penggunaan Lokasi'. Informasi lebih lanjut tentang tautan: developer.apple.com/library/ios/documentation/General/Reference/…
Sihad Begovic
79

Di iOS 6, the

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

sudah ditinggalkan.

Gunakan kode berikut sebagai gantinya

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
    CLLocation *location = [locations lastObject];
    NSLog(@"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
}

Untuk iOS 6 ~ 8, metode di atas masih diperlukan, tetapi Anda harus menangani otorisasi.

_locationManager = [CLLocationManager new];
_locationManager.delegate = self;
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 &&
    [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse
    //[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways
   ) {
     // Will open an confirm dialog to get user's approval 
    [_locationManager requestWhenInUseAuthorization]; 
    //[_locationManager requestAlwaysAuthorization];
} else {
    [_locationManager startUpdatingLocation]; //Will update location immediately 
}

Ini adalah metode delegasi yang menangani otorisasi pengguna

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
    case kCLAuthorizationStatusNotDetermined: {
        NSLog(@"User still thinking..");
    } break;
    case kCLAuthorizationStatusDenied: {
        NSLog(@"User hates you");
    } break;
    case kCLAuthorizationStatusAuthorizedWhenInUse:
    case kCLAuthorizationStatusAuthorizedAlways: {
        [_locationManager startUpdatingLocation]; //Will update location immediately
    } break;
    default:
        break;
    }
}
Ryan Wu
sumber
10
bukankah ini seharusnya [locations lastObject]?
Ian Dundas
1
Saya mencoba langkah-langkah yang persis sama yang disebutkan di atas. Tapi saya mendapatkan "Pengguna masih berpikir" dicetak di konsol. Jadi, apakah itu berarti aplikasi tidak diizinkan untuk menggunakan lokasi? Jika ya, bagaimana cara saya mengizinkan aplikasi untuk menggunakan lokasi. Tolong bantu.
kirans_6891
31

Coba Langkah Sederhana ini ....

CATATAN: Silakan periksa garis lintang lokasi & logitude jika Anda menggunakan cara simulator. Secara default tidak ada.

Langkah 1: Impor CoreLocationkerangka kerja dalam file .h

#import <CoreLocation/CoreLocation.h>

Langkah 2: Tambahkan delegasi CLLocationManagerDelegate

@interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
}

Langkah 3: Tambahkan kode ini dalam file kelas

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self CurrentLocationIdentifier]; // call this method
}

Langkah 4: Metode untuk mendeteksi lokasi saat ini

//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
    //---- For getting current gps location
    locationManager = [CLLocationManager new];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];
    //------
}

Langkah 5: Dapatkan lokasi menggunakan metode ini

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    currentLocation = [locations objectAtIndex:0];
    [locationManager stopUpdatingLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
     {
         if (!(error))
         {
             CLPlacemark *placemark = [placemarks objectAtIndex:0];
             NSLog(@"\nCurrent Location Detected\n");
             NSLog(@"placemark %@",placemark);
             NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
             NSString *Address = [[NSString alloc]initWithString:locatedAt];
             NSString *Area = [[NSString alloc]initWithString:placemark.locality];
             NSString *Country = [[NSString alloc]initWithString:placemark.country];
             NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country];
             NSLog(@"%@",CountryArea);
         }
         else
         {
             NSLog(@"Geocode failed with error %@", error);
             NSLog(@"\nCurrent Location Not Detected\n");
             //return;
             CountryArea = NULL;
         }
         /*---- For more results 
         placemark.region);
         placemark.country);
         placemark.locality); 
         placemark.name);
         placemark.ocean);
         placemark.postalCode);
         placemark.subLocality);
         placemark.location);
          ------*/
     }];
}
Rajesh Loganathan
sumber
14

Dalam Swift (untuk iOS 8+).

Info.plist

Hal pertama yang pertama. Anda perlu menambahkan string deskriptif dalam file info.plist untuk kunci NSLocationWhenInUseUsageDescriptionatau NSLocationAlwaysUsageDescriptiontergantung pada jenis layanan yang Anda minta

Kode

import Foundation
import CoreLocation

class LocationManager: NSObject, CLLocationManagerDelegate {
    
    let manager: CLLocationManager
    var locationManagerClosures: [((userLocation: CLLocation) -> ())] = []
    
    override init() {
        self.manager = CLLocationManager()
        super.init()
        self.manager.delegate = self
    }
    
    //This is the main method for getting the users location and will pass back the usersLocation when it is available
    func getlocationForUser(userLocationClosure: ((userLocation: CLLocation) -> ())) {
        
        self.locationManagerClosures.append(userLocationClosure)
        
        //First need to check if the apple device has location services availabel. (i.e. Some iTouch's don't have this enabled)
        if CLLocationManager.locationServicesEnabled() {
            //Then check whether the user has granted you permission to get his location
            if CLLocationManager.authorizationStatus() == .NotDetermined {
                //Request permission
                //Note: you can also ask for .requestWhenInUseAuthorization
                manager.requestWhenInUseAuthorization()
            } else if CLLocationManager.authorizationStatus() == .Restricted || CLLocationManager.authorizationStatus() == .Denied {
                //... Sorry for you. You can huff and puff but you are not getting any location
            } else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
                // This will trigger the locationManager:didUpdateLocation delegate method to get called when the next available location of the user is available
                manager.startUpdatingLocation()
            }
        }
        
    }
    
    //MARK: CLLocationManager Delegate methods
    
    @objc func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
            manager.startUpdatingLocation()
        }
    }
    
    func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
        //Because multiple methods might have called getlocationForUser: method there might me multiple methods that need the users location.
        //These userLocation closures will have been stored in the locationManagerClosures array so now that we have the users location we can pass the users location into all of them and then reset the array.
        let tempClosures = self.locationManagerClosures
        for closure in tempClosures {
            closure(userLocation: newLocation)
        }
        self.locationManagerClosures = []
    }
}

Pemakaian

self.locationManager = LocationManager()
self.locationManager.getlocationForUser { (userLocation: CLLocation) -> () in
            print(userLocation)
        }
villy393
sumber
8
Saya percaya ada saklar () di swift untuk kasus-kasus seperti ini: ^)
Anton Tropashko
self.locationManager = LocationManager()gunakan baris ini dalam metode viewDidLoad sehingga ARC tidak menghapus instance dan popup untuk lokasi menghilang terlalu cepat.
Kunal Gupta
2

iOS 11.x Swift 4.0 Info.plist membutuhkan dua properti ini

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>We're watching you</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Watch Out</string>

Dan kode ini ... memastikan tentu saja Anda seorang CLLocationManagerDelegate Anda

let locationManager = CLLocationManager()

// MARK location Manager delegate code + more

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch status {
    case .notDetermined:
        print("User still thinking")
    case .denied:
        print("User hates you")
    case .authorizedWhenInUse:
            locationManager.stopUpdatingLocation()
    case .authorizedAlways:
            locationManager.startUpdatingLocation()
    case .restricted:
        print("User dislikes you")
    }

Dan tentu saja kode ini juga bisa Anda masukkan ke dalam viewDidLoad ().

locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestLocation()

Dan dua ini untuk requestLocation untuk membuat Anda pergi, alias menghemat Anda harus keluar dari tempat duduk Anda :)

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print(error)
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print(locations)
}
pengguna3069232
sumber
1

Anda dapat menggunakan layanan ini yang saya tulis untuk menangani semuanya untuk Anda.

Layanan ini akan meminta izin dan menangani berurusan dengan CLLocationManager sehingga Anda tidak perlu melakukannya.

Gunakan seperti ini:

LocationService.getCurrentLocationOnSuccess({ (latitude, longitude) -> () in
    //Do something with Latitude and Longitude

    }, onFailure: { (error) -> () in

      //See what went wrong
      print(error)
})
William Falcon
sumber
0

Untuk Swift 5, berikut ini kelas singkat untuk mendapatkan lokasi:

class MyLocationManager: NSObject, CLLocationManagerDelegate {
    let manager: CLLocationManager

    override init() {
        manager = CLLocationManager()
        super.init()
        manager.delegate = self
        manager.distanceFilter = kCLDistanceFilterNone
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // do something with locations
    }
}
Dave Elson
sumber