close

開發平台:Mac mini OS X Yosemite 10.10.5

開發軟體:Xcode 7.0(7B91b) 

開發裝置:iPhone 5S -iOS 9.1(13B143) 

最近正在研究iBeacon(BLE or Bluetooth 4.0),

因為看到有關於iBeacon的APP都會在你開啟APP時詢問你:

(1).開啟藍芽來允許「your APP」連接配件->這是提醒你必須開啟藍芽方能使用APP

(2).要允許「your APP」在您使用時取用您的位置嗎?->這是提醒你必須開啟定位服務方能使用APP


Step1.增加需要用到的兩個framework(CoreBluetooth,CoreLocation)


Step2.開啟所需要的Background Modes,點選TARGETS>Capabilities>Background Modes>勾選Location updates

Step3.到Info.plist裡增加NSLocationWhenInUseUsageDescription>後面字串可以描述此功能的用途

Step4.使用CoreBluetooth Framework中,主要管理連線的是CBCentralManager這個Object,它掌控整個BLE狀態的管理,使用時要先對CBCentralManager初始化:

首先到AppDelegate.h,新增下列的code

#import <CoreBluetooth/CoreBluetooth.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate,CBCentralManagerDelegate>

@property (strong, nonatomic) CBCentralManager *CM;

再來到AppDelegate.m對CBCentralManager初始化:

CBCentralManager *CM = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

完成之後就可以測試看看,應該就能得到開啟藍芽的允許了!

Step5.定位服務基於CoreLocation框架,定位時主要使用CLLocationManager、CLLocationManagerDelegate和CLLocation,其中CLLocationManager是定位服務管理類

因此先到viewController.h

#import <CoreLocation/CoreLocation.h>//添加定位服務.h文件(不可缺少)

@interface ViewController : UIViewController<CLLocationManagerDelegate,UIAlertViewDelegate>

再來到viewController.m

- (void)viewDidLoad {

    [super viewDidLoad];

_locationManager = [[CLLocationManager alloc] init]; //建立CLLocationManager對象

_locationManager.delegate = self;                    //設置代理,這樣函數didUpdateLocations才會被回調

    [_locationManager requestWhenInUseAuthorization];    //詢問是否要給APP有定位功能權限

    [_locationManager startUpdatingLocation];            //開啟計算目前行動裝置所在位置的功能

}

這樣就可以完成允許定位服務囉!



arrow
arrow

    JoshJhan 發表在 痞客邦 留言(0) 人氣()