现象:
使用CLLocationManager定位。
//
// GPSViewController.m
// Fly Survey
//
// Created by dinghongyan on 13-7-5.
//
//
#import "GPSViewController.h"
#import "ZYFileUtil.h"
#import "ZYDateUtil.h"
#import <CoreLocation/CoreLocation.h>
#import "ZYMyLog.h"
@interface GPSViewController ()<CLLocationManagerDelegate>
@end
@implementation GPSViewController
-(id)init{
if (self = [super init]) {
if ([CLLocationManager locationServicesEnabled]) {
self.lm = [[CLLocationManager alloc] init];
self.lm.delegate = self;
self.lm.desiredAccuracy = kCLLocationAccuracyBest;
}
}
return self;
}
-(void)startGPS{
if (self.lm) {
[self.lm startUpdatingLocation];
}
}
-(void)stopGPS{
if (self.lm) {
[self.lm stopUpdatingLocation];
}
}
//iOS6.0以上推荐使用方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,如果不想让其持续更新位置,则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
CLLocation *currentLocation = [locations lastObject];
[self saveLocation:currentLocation];
}
//iOS6.0以下
- (void) locationManager: (CLLocationManager *) manager
didUpdateToLocation: (CLLocation *) newLocation
fromLocation: (CLLocation *) oldLocation{
[self saveLocation:newLocation];
}
- (void)saveLocation:(CLLocation *)newLocation
{
//纬度
NSString *latitude = [[NSString alloc] initWithFormat:@"%f",newLocation.coordinate.latitude];
//经度
NSString *longitude = [[NSString alloc] initWithFormat:@"%f",newLocation.coordinate.longitude];
//保存定位信息
NSString *timeNow = [ZYDateUtil timeNow:@"yyyy-MM-dd HH:mm:ss"];
[[ZYMyLog sharedMyLog] appendString:[NSString stringWithFormat:@"更新位置:(%@,%@)",latitude,longitude]];
self.longitude = longitude;
self.latitude = latitude;
self.time = timeNow;
}
- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSString *timeNow = [ZYDateUtil timeNow:@"yyyy-MM-dd HH:mm:ss"];
[[ZYMyLog sharedMyLog] appendString:[NSString stringWithFormat:@"定位出错:%@",error]];
self.time = timeNow;
self.longitude = @"";
self.latitude = @"";
[self.lm stopUpdatingLocation];
}
@end
iPhone有手机卡,开启GPS和WIFI,可以很快定位。
iPhone没有手机卡,开启GPS和WIFI,1分钟内无法定位。
iPad开启GPS和WIFI,1分钟内无法定位。(室外)
暂时无解。
2015-1-28更新:
其实跟手机什么状态没有关系。恰好有手机卡的iPhone是7.1的,而没有手机卡的iPhone和iPad都是8.0以上的,因此看起来奇怪。
实际的原因是,iOS 8中定位有了变化。导致iOS 7可用,iOS 8定位失败。
iOS 8的适配见:http://blog.csdn.net/hzxpyjq/article/details/43231435