dpl*_*usm 336

RedBlueThing的答案对我来说非常好.以下是我如何做到的一些示例代码.

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

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

@end
Run Code Online (Sandbox Code Playgroud)

MainFile

在init方法中

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
Run Code Online (Sandbox Code Playgroud)

回调函数

- (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);
}
Run Code Online (Sandbox Code Playgroud)

iOS 6

在iOS 6中,不推荐使用委托功能.新代表是

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
Run Code Online (Sandbox Code Playgroud)

因此要获得新职位的使用

[locations lastObject]
Run Code Online (Sandbox Code Playgroud)

iOS 8

在iOS 8中,应在开始更新位置之前明确询问权限

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];
Run Code Online (Sandbox Code Playgroud)

您还必须为应用程序的Info.plist 添加NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription键的字符串.否则startUpdatingLocation将忽略调用,您的代理将不会收到任何回调.

最后,当您完成阅读位置调用stopUpdating位置在适当的地方.

[locationManager stopUpdatingLocation];
Run Code Online (Sandbox Code Playgroud)

  • 重要提示:您还需要"stopUpdatingLocations",否则每次用户更改其位置时都会调用委托方法.因此上面提到的电池问题以及如果在该委托方法中触发了另一种方法,它将保持呼叫.快乐的编码家伙!! 干杯!! (36认同)
  • 对于iOS 8.0+,您必须在项目的Info.plist中包含以下键:`NSLocationAlwaysUsageDescription`如果您使用`[self.locationManager requestAlwaysAuthorization]`或`NSLocationWhenInUseUsageDescription`,如果您使用`[self.locationManager requestWhenInUseAuthorization]`.此外,为了支持iOS 6.0+到iOS 7.0+,还包括密钥`NSLocationUsageDescription`或'Privacy - Location Usage Description'.有关链接的更多信息:https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html (26认同)
  • 请注意此示例,这些属性值会导致更高的电池消耗. (12认同)
  • 您是使StackOverflow变得更棒的用户类型.代码片段是示例性的,我希望更多人将他们的答案包括在内. (5认同)
  • +1感谢您发布一个简单的代码段来赞美接受的答案 (4认同)

Rya*_* Wu 77

在iOS 6中,

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
Run Code Online (Sandbox Code Playgroud)

已弃用.

请改用以下代码

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

对于iOS 6~8,上述方法仍然是必需的,但您必须处理授权.

_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 
}
Run Code Online (Sandbox Code Playgroud)

这是处理用户授权的委托方法

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这不应该是`[locations lastObject]`吗? (10认同)

Red*_*ing 61

您可以使用CoreLocation框架来访问有关用户的位置信息.您需要实例化CLLocationManager对象并调用异步startUpdatingLocation消息.您将通过您提供的CLLocationManagerDelegate获取用户位置的回调.


Raj*_*han 31

试试这个简单的步骤....

注意:如果您使用的是模拟器,请检查设备位置的纬度和度数.默认情况下,它不是唯一的.

第1步:CoreLocation在.h文件中导入框架

#import <CoreLocation/CoreLocation.h>
Run Code Online (Sandbox Code Playgroud)

第2步:添加委托CLLocationManagerDelegate

@interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
}
Run Code Online (Sandbox Code Playgroud)

第3步:在类文件中添加此代码

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self CurrentLocationIdentifier]; // call this method
}
Run Code Online (Sandbox Code Playgroud)

步骤4:检测当前位置的方法

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

第5步:使用此方法获取位置

- (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);
          ------*/
     }];
}
Run Code Online (Sandbox Code Playgroud)


vil*_*393 14

在Swift中(适用于iOS 8+).

的Info.plist

首先要做的事情.您需要在info.plist文件中为密钥添加描述性字符串,NSLocationWhenInUseUsageDescription或者NSLocationAlwaysUsageDescription根据您请求的服务类型添加

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 = []
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

self.locationManager = LocationManager()
self.locationManager.getlocationForUser { (userLocation: CLLocation) -> () in
            print(userLocation)
        }
Run Code Online (Sandbox Code Playgroud)

  • 我相信在这样的情况下swift中有一个switch():^) (8认同)

def*_*yte 12

Xcode文档具有丰富的知识和示例应用程序 - 请查看位置感知编程指南.

LocateMe示例项目说明修改的效果CLLocationManager的不同精度设置