Core Location在iOS 8中的變化---Swift

來源:互聯網
上載者:User

標籤:des   style   blog   http   ar   io   color   os   使用   

一直以來,定位的實現都非常的簡單和一致:

Objective-C的實現:

#import "ViewController.h"@import CoreLocation; //引入庫檔案@interface ViewController () <CLLocationManagerDelegate> //遵守協議@property (strong, nonatomic) CLLocationManager *locationManager; //定義Location Manager@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    //初始化Manager並開始定位    self.locationManager = [[CLLocationManager alloc] init];    self.locationManager.delegate = self;    [self.locationManager startUpdatingLocation];}//Delegate的協議方法- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{    NSLog(@"%@", [locations lastObject]);}- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{    NSLog(@"error = %@",[error description]);}@end


Swift的實現:
import UIKitimport CoreLocationclass ViewController: UIViewController, CLLocationManagerDelegate {        let locationManager:CLLocationManager = CLLocationManager()        override func viewDidLoad() {        super.viewDidLoad()        locationManager.delegate = self        locationManager.startUpdatingLocation();    }        func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {        println("new Location = \(locations.last)")    }        func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {        println("error = \(error.description)")    }}
但是在iOS8的情況下,任何代理方法都是沉默的---既不能得到失敗的原因或者警告,也不能得到位置資訊.App也不會有請求允許使用位置資訊的許可.非常的和諧.
在iOS8的系統中需要做兩件事情才能讓定位能夠生效:

1. 在Info.plist添加一對關鍵字來許可位置服務.NSLocationAlwaysUsageDescription和NSLocationWhenInUseUsageDescription,兩個關鍵字對應的字串可以是隨意的,一般只要添加一個關鍵字即可,因為有AlwaysUsage那麼WhenInUse情況下也能定位,反之則不能適用.

2. 在代碼中請求許可.

Objective-C的實現:

    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {        [self.locationManager requestWhenInUseAuthorization];    }    //或者    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {        [self.locationManager requestAlwaysAuthorization];    }
Swift的實現:

        //iOS8中的方法,不然是無法定位的        if locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization")) {            locationManager.requestWhenInUseAuthorization()        }        //或者        if locationManager.respondsToSelector(Selector("requestAlwaysAuthorization")) {            locationManager.requestAlwaysAuthorization()        }

更改地理位置的認證狀態

如果最開始的時候設定的是WhenInUse, 而後需要使用Always,那麼就需要在Plist和代碼中更改狀態

Objective-C的實現:

if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {        [self requestAlwaysAuthorization];    }
- (void)requestAlwaysAuthorization{    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];    //如果狀態是沒有獲准就彈出一個Alert    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {        NSString *title;        title = (status == kCLAuthorizationStatusDenied) ? @"定位是關閉狀態" : @"後台定位沒有開啟";        NSString *message = @"需要開啟Alway的定位服務";        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title                                                            message:message                                                           delegate:self                                                  cancelButtonTitle:@"取消"                                                  otherButtonTitles:@"設定", nil];        [alertView show];    }    else if (status == kCLAuthorizationStatusNotDetermined) {        [self.locationManager requestAlwaysAuthorization];    }}- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{    if (buttonIndex == 1) {        // 跳到設定介面        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];        [[UIApplication sharedApplication] openURL:settingsURL];    }}
Swift的實現:
        if locationManager.respondsToSelector(Selector("requestAlwaysAuthorization")) {            requestAlwaysAuthorization()        }
    func requestAlwaysAuthorization() {        let status = CLLocationManager.authorizationStatus()        if status == .Denied || status == .AuthorizedWhenInUse {            let title = (status == .Denied) ? "定位是關閉狀態" : "後台定位沒有開啟"            let message = "需要開啟Alway的定位服務"            UIAlertView(title: title, message: message, delegate:self, cancelButtonTitle: "取消", otherButtonTitles: "設定")        } else {            locationManager.requestAlwaysAuthorization()        }    }        func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {        if buttonIndex == 1 {            UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)        }    }

Core Location在iOS 8中的變化---Swift

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.