该app为应用的功能为用iPhone 显示你现在的位置
现版本 SDK 8.4 Xcode
运行Xcode 选择 Create a new Xcode project ->Single View Application 命名 WhereAmI
(1) 点击文件夹WhereAmI -> General->Linked Frameworks and Libraries -> "+"-> 搜索 CoreLocation.framework ->add
(2) 打开 ViewController.h 文件,加入下面代码
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <CoreLocation/CLLocationManagerDelegate.h>
@interface ViewController : UIViewController <CLLocationManagerDelegate>{
IBOutlet UITextField *altitude;
IBOutlet UITextField *latitude;
IBOutlet UITextField *longitude;
CLLocationManager *locmanager;
BOOL wasFound;
}
-(IBAction)update:(id)sender;
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *) oldLocation ;
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *) error;
@end
(3) 打开 ViewController.m 文件,加入下面代码
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
-(IBAction)update:(id)sender{
locmanager = [[CLLocationManager alloc]init];
[locmanager setDelegate:self];
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];
locmanager.distanceFilter=10;
NSString *iOSVersion=[UIDevice currentDevice].systemVersion;
//NSLog(@"%@",iOSVersion);
if ((int)iOSVersion >= 8) {
[locmanager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据(iOS8定位需要)
}
[locmanager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
if(wasFound)return;
wasFound = YES;
CLLocationCoordinate2D loc = [newLocation coordinate];
latitude.text = [NSString stringWithFormat:@"%f",loc.latitude];
longitude.text = [NSString stringWithFormat:@"%f",loc.longitude];
altitude.text = [NSString stringWithFormat:@"%f",newLocation.altitude];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
(3) 设置info.plist
点击info.plist,在右侧添加NSLocationWhenInUseUsageDescription和NSLocationAlwaysUsageDescription
将 Value设置为YES
(4) UIView 界面设置
点击Main.storyboard
加入三个Label 在 Attributes 下, Text 内填上"经度",“纬度”,“海拔”;
加入 三个Text Field用于显示 "经度",“纬度”,“海拔”;
鼠标右击Text Field控件 移动鼠标在"Referencing Outlets" 后面圆圈上; 圆圈变为(+); 拖动直线连接到"view controller";
放开鼠标选择键出现 "longitude","latitude","altitude"; 对应着"经度",“纬度”,“海拔”三个Text Field ,分别选上它。
选择: File -> Save
最后在 xCode 选择 Build and then Running
(5)真机调试效果图
本文源于网上博客教程,经过本人修改和测试。原blog地址 http://blog.sina.com.cn/s/blog_5fae23350100e5fi.html