iOS高级技术iOS个人修养iOS开发

iOS后台持续定位实现方法

2015-11-27  本文已影响5019人  CGPointZero

1.选中target-->Gapability,打开Background Modes模式,并勾选Location updates

设置

2.代码如下:

ViewController.h
<pre>#import <UIKit/UIKit.h>

import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController<CLLocationManagerDelegate>

//定位管理对象
@property(nonatomic,strong)CLLocationManager *manager;

@end</pre>
ViewController.m
<pre>#import "ViewController.h"

@interface ViewController ()
{
CLGeocoder *_coder;
//存储上一次的位置
}
@end

@implementation ViewController

}

pragma mark-CLLocationManager代理方法

//定位失败时调用的方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"%@",error);
}
//定位成功调用的的方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
if(locations.count>0)
{
// 获取位置信息
CLLocation *loc=[locations lastObject];
// 获取经纬度的结构体
CLLocationCoordinate2D coor=loc.coordinate;

    CLLocation *location=[[CLLocation alloc]initWithLatitude:coor.latitude longitude:coor.longitude];
    
    [_coder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *pmark=[placemarks firstObject];
        NSLog(@"%@",pmark.addressDictionary);
        NSString *city=pmark.addressDictionary[@"City"];
        if([city hasSuffix:@"市辖区"])
            city=[city substringToIndex:city.length-3];
        if([city hasSuffix:@"市"])
            city=[city substringToIndex:city.length-1];
        NSLog(@"%@",city);
    }];
}

}
@end</pre>
Appdelegate.m
<pre>#import "AppDelegate.h"

import <CoreLocation/CoreLocation.h>

import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

@end</pre>

上一篇 下一篇

猜你喜欢

热点阅读