viewcontroller.m//bleex2////Created By my future is not dream on 14-11-26.//Copyright (c) 2014 choicemmed. All rights reserved.//#import "ViewController.h"//1 head file #import <CoreBluetooth/CoreBluetooth.h> @interface Viewcontroller () <cbcentralmanagerdelegate, cbperipheraldelegate>
@property (nonatomic, strong) Cbcentralmanager *mgr; @property (nonatomic, strong) Nsmutablearray *peripherals;
@end @implementation viewcontroller-(Nsmutablearray *) peripherals{if (!_peripherals) {_peripherals = [nsmutab Learray array]; } return _peripherals;} -(void) Viewdidload {
[Super Viewdidload]; 2 Creating a central Manager object Cbcentralmanager *mgr = [[Cbcentralmanager alloc] init]; Mgr.delegate = self; Self.mgr = Mgr; 3 Scan Peripheral Parameters nil means search all peripherals [Mgr Scanforperipheralswithservices:nil Options:nil]; }//Analog connection peripherals-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{//scan peripherals for services and features for (Cbperipheral *perip Heral in self.peripherals) {peripheral.delegate = self;
Connecting peripherals using Mgr [Self.mgr connectperipheral:peripheral Options:nil]; }} #pragma mark-cbcentralmanagerdelegate//Center management scan to peripheral-(void) Centralmanager: (Cbcentralmanager *) Central Diddiscoverperipheral: (cbperipheral *) Peripheral Advertisementdata: (nsdictionary *) Advertisementdata RSSI: ( NSNumber *) rssi{//The peripheral is saved if (![ Self.peripherals Containsobject:peripheral]) {[Self.peripherals addobject:peripheral]; }}//center Management Connection Peripheral succeeded (void) Centralmanager: (Cbcentralmanager *) Central didconnectperipheral: (cbperipheral *) peripheral{// Scanning for services in peripherals [peripheral discoverservices:nil];} Center Management Connection Peripheral failed-(void) Centralmanager: (Cbcentralmanager *) Central diddisconnectperipheral: (cbperipheral *) Peripheral Error: (Nserror *) error{NSLog (@ "%@", error),} #pragma mark-cbperipheraldelegate//peripheral scan to service-(void) Peripheral: (Cbperiph eral *) Peripheral diddiscoverservices: (Nserror *) error{nsarray *services = peripheral.services; For (Cbservice *service in Services) {//Get required services if ([@ "Needservice" Isequaltostring:service. Uuid. Uuidstring]) {[Peripheral discovercharacteristics:nil forservice:service]; }}}-(void) Peripheral: (cbperipheral *) Peripheral Diddiscovercharacteristicsforservice: (Cbservice *) Service error: ( Nserror *) error{nsarray *characteristics = service.characteristics; For (cbcharacteristic *characteristic in characteristics) {if ([@ "Needcharacteristic" isequaltostring:characterist Ic. Uuid. Uuidstring]) {NSLog (@ "do somthing~"); }}} @end
The BLE development process in iOS