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

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

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 UIKit
import CoreLocation

class 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)!)
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章