Jawaban:
Jawaban RedBlueThing bekerja cukup baik untuk saya. Berikut adalah beberapa contoh kode tentang bagaimana saya melakukannya.
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
@end
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);
}
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]
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 NSLocationAlwaysUsageDescription
atau NSLocationWhenInUseUsageDescription
kunci ke Info.plist aplikasi. Kalau tidak, panggilan ke startUpdatingLocation
akan 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];
NSLocationAlwaysUsageDescription
jika Anda menggunakan [self.locationManager requestAlwaysAuthorization]
atau NSLocationWhenInUseUsageDescription
jika Anda menggunakan [self.locationManager requestWhenInUseAuthorization]
. Juga untuk mendukung iOS 6.0+ ke iOS 7.0+ termasuk kunci NSLocationUsageDescription
atau 'Privasi - Deskripsi Penggunaan Lokasi'. Informasi lebih lanjut tentang tautan: developer.apple.com/library/ios/documentation/General/Reference/…
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;
}
}
[locations lastObject]
?
Anda menggunakan kerangka kerja CoreLocation untuk mengakses informasi lokasi tentang pengguna Anda. Anda harus membuat instance a objek CLLocationManager dan memanggil pesan startUpdatingLocation asynchronous . Anda akan mendapatkan panggilan balik dengan lokasi pengguna melalui CLLocationManagerDelegate yang Anda berikan.
CATATAN: Silakan periksa garis lintang lokasi & logitude jika Anda menggunakan cara simulator. Secara default tidak ada.
Langkah 1: Impor CoreLocation
kerangka 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);
------*/
}];
}
Info.plist
Hal pertama yang pertama. Anda perlu menambahkan string deskriptif dalam file info.plist untuk kunci NSLocationWhenInUseUsageDescription
atau NSLocationAlwaysUsageDescription
tergantung 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)
}
self.locationManager = LocationManager()
gunakan baris ini dalam metode viewDidLoad sehingga ARC tidak menghapus instance dan popup untuk lokasi menghilang terlalu cepat.
Dokumentasi Xcode memiliki banyak pengetahuan dan contoh aplikasi - lihat Panduan Pemrograman Kesadaran Lokasi .
The LocateMe proyek sampel menggambarkan efek dari memodifikasi CLLocationManager pengaturan akurasi 's berbeda
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)
}
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)
})
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
}
}