標籤:
該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
四、衛星定位《蘋果iOS執行個體編程入門教程》