如何从iOS中获取用户的当前位置

编程入门 行业动态 更新时间:2024-10-26 20:26:16
本文介绍了如何从iOS中获取用户的当前位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何从iOS中的用户获取当前位置?

How can I get the current location from user in iOS?

推荐答案

RedBlueThing的答案对我来说效果很好。以下是我如何做到的一些示例代码。

The answer of RedBlueThing worked quite well for me. Here is some sample code of how I did it.

#import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> @interface yourController : UIViewController <CLLocationManagerDelegate> { CLLocationManager *locationManager; } @end

MainFile

在init方法中

MainFile

In the init method

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

回调函数

- (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

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

iOS 6

In iOS 6 the delegate function was deprecated. The new delegate is

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

因此,要获得新职位,请使用

Therefore to get the new position use

[locations lastObject]

iOS 8

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

iOS 8

In iOS 8 the permission should be explicitly asked before starting to update location

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];

您还必须为 NSLocationAlwaysUsageDescription 或 NSLocationWhenInUseUsageDescription 应用程序Info.plist的键。否则,将忽略对 startUpdatingLocation 的调用,并且您的代理人将不会收到任何回调。

You also have to add a string for the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription keys to the app's Info.plist. Otherwise calls to startUpdatingLocation will be ignored and your delegate will not receive any callback.

并且当你结束时完成读取位置调用stopUpdating位置在适当的位置。

And at the end when you are done reading location call stopUpdating location at suitable place.

[locationManager stopUpdatingLocation];

更多推荐

如何从iOS中获取用户的当前位置

本文发布于:2023-06-07 21:54:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/568450.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:当前位置   用户   iOS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!