First, the earliest Bluetooth framework was used before GAMEKIT,IOS7, it has only supported the transfer between iOS devices, but the use of simple steps, we just need to figure out two classes to be able to.
Gkpeerpickercontroller: Mature Browser, call this controller's Show method to display the current Bluetooth hotspot, once found that there is another page in the search for Bluetooth users, can be real link.
Gksession: A connection session that is used primarily for sending and receiving transmitted data. When two programs are connected, the Gkpeerpickercontroller proxy method passes the established session (Gksession) object to the established object. To achieve data transfer.
Below to build a simple and simple Bluetooth send
1.1 First build a Bluetooth controller that can display the area.
-(void) Connecttootherbluetoolth { //1. First build a region can display other Bluetooth controller, our phone select Bluetooth list is actually the corresponding operation is this controller, it can listen to my operation. gkpeerpickercontroller* PEERVC = [Gkpeerpickercontroller new]; Peervc.delegate = self; [PEERVC show];}
1.2 Through this real-world controller proxy method to listen to the success of the link, if the success of the link to save the pipeline, and design a sentence for it bin
-(void) Peerpickercontroller: (Gkpeerpickercontroller *) Picker Didconnectpeer: (NSString *) Peerid toSession: ( Gksession *) session { //2. To handle the message after the link succeeds by implementing the Gkpeerpickercontroller proxy method; Here we go. Session object sessions are preserved, It should be equivalent to a transport pipeline, the function and the QR code to scan the same pipeline. self.session = session; 3. At this point we also need to develop a method to receive data. This function can be easily understood as a proxy-like function, which means to set a hander (sentence bin) to the session pipe object, which must implement a method of receiving data. [Session setdatareceivehandler:self Withcontext:nil];}
1.3 The method of implementing this sentence bin can simply be understood as a protocol method similar to
4. Use the Self object to implement the method specified by the clause bin-(void) Receviedata: (NSData *) data frompeer: (nsstring*) Peer insession: (gksession*) session Context: (void *) Context { uiimage* image = [UIImage imagewithdata:data]; Self.imageView.image = image;}
1.4 Then we only need to send the image after the link success and can create a picture controller--set agent, whether to support the selection method, make the choice of the image-"to achieve the choice of completion method, from the dictionary to obtain the selected picture
-(void) Chooserimage {/* Select a picture from the album to create a picture selection controller-"Determine whether you can use-" to set the type of Open Picture library-"Processing this action needs to implement the relevant method, so here need to set the image controller Agent */ uiimagepickercontroller* Imagepiker = [Uiimagepickercontroller new]; if ([Uiimagepickercontroller issourcetypeavailable:uiimagepickercontrollersourcetypesavedphotosalbum]) {ImagePike R.sourcetype = Uiimagepickercontrollersourcetypesavedphotosalbum; Imagepiker.delegate = self; }} #pragma mark-uiimagepikercontrollerdelegate-(void) Imagepickercontroller: (Uiimagepickercontroller *) picker Didfinishpickingmediawithinfo: (nsdictionary<nsstring *,id> *) Info {///Here is the option to select a picture, the selected picture can be removed from a key. Self.imageView.image = Info[uiimagepickercontrolleroriginalimage]; The controller that pops up is turned off. [Picker Dismissviewcontrolleranimated:yes Completion:nil]; }//3. Send picture data-(void) Sendimage {//send uiimage* image = Self.imageView.image with the link successful Session object; nsdata* data = uiimagepngrepresentation (image); [Self.session senddata:data Topeers:nil WithdatamOde:gksenddatareliable Error:nil];}
Two. Mutipeerconnectivity:
Literally multi-hotspot links. The thing Apple has come up with is a real substitute for gamekit. It doesn't just support Bluetooth connectivity. It belongs to a local area network that deplores the loss, shielding the specific link technology. By multipeerconnectivity linking nodes, you can make file resource delivery independent of the network. It is implemented primarily through adveristing and disconvering, similar to the interactive response between the client and server side. Send a broadcast through one object sends a message, while another object accepts a message as a customer. After the agreement between the two agreed to achieve the docking. The link between the Gamekit and its doors also requires a dedicated pipe mcsession. Used to receive and pass data. The two ends of the pipe correspond to the mcpeerid, and the markings between the devices.
We only need to set the proxy for the session object and listen for the status of the session (whether it is online), and whether or not to receive data. In fact, this is the same as the socket socket byte usage.
Figuring out the basic principle name we just need to be familiar with the next few methods and key words to be able to exercise skillfully.
2.1 Set the basic properties and controls.
@interface Viewcontroller () <mcsessiondelegate,mcadvertiserassistantdelegate,mcbrowserviewcontrollerdelegate, Uitextfielddelegate> @property (Weak, nonatomic) Iboutlet UIButton *browserbutton; @property (weak, nonatomic) Iboutlet Uitextfield *chatbox; @property (weak, nonatomic) Iboutlet Uitextview *textbox;//Device ID, Used to indicate the device identification information for sending broadcasts and receiving broadcast messages @property (strong,nonatomic) Mcpeerid *myperrid;//Connection session for maintaining the current session persistent link @property (strong, nonatomic) mcsession *mysession;//broadcast object, created after it needs to be opened before sending the broadcast, it has two protocol methods, will send broadcast and has sent broadcast @property (strong,nonatomic) Mcadvertiserassistant *advertiserassistant;//Select the session controller, the timing is to select a list of Bluetooth hotspots, it can listen to our choice of which hotspot @property (strong,nonatomic) Mcbrowserviewcontroller *browserviewcontroller; @end
2.2 Setting Mcpeerid,mcadvertiserassistant (Broadcast object creation and startup)
static NSString *servicetype = @ "chat";-(void) setupmutipeer{ self.myperrid = [[Mcpeerid alloc]initwithdisplayname : [Uidevice currentdevice].name]; Self.mysession = [[Mcsession Alloc]initwithpeer:self.myperrid]; Self.advertiserassistant = [[Mcadvertiserassistant alloc]initwithservicetype:servicetype DiscoveryInfo:nil session: Self.mysession]; Self.browserviewcontroller = [[Mcbrowserviewcontroller alloc]initwithservicetype:servicetype session: Self.mysession]; Self.browserViewController.delegate = self; Self.mySession.delegate = self; [Self.advertiserassistant start];}
2.3 Set the Sessionde proxy method whether the channel is linked OK, whether it has received data, set Mcbrowserviewcontroller whether the Bluetooth hotspot is selected, and Dissmiss the controller.
Display Controller view-(void) showbroservc{[self PresentViewController:self.browserViewController animated:yes Completion:nil ];} Cancel Controller-(void) dismissbrowservc{[Self.browserviewcontroller dismissviewcontrolleranimated:yes completion:nil];} Click the browser button-(ibaction) Browserbtnclick: (ID) Sender {[self SHOWBROSERVC];} Send text-(void) sendtext{nsstring *message = Self.chatBox.text; Self.chatBox.text = @ ""; NSData *data = [message datausingencoding:nsutf8stringencoding]; Send via session [Self.mysession Senddata:data topeers:[self.mysession connectedpeers] withmode:mcsessionsenddatareliable er Ror:nil]; Collect data [self recivemessage:message FromPeer:self.myPerrID];} Collect data-(void) Recivemessage: (nsstring*) message frompeer: (mcpeerid*) perrid{nsstring *finalmessage = nil; if (Perrid = = Self.myperrid) {finalmessage = [nsstring stringwithformat:@ "\nme:%@\n", message]; }else{finalmessage = [NSString stringwithformat:@ "\n%@:%@\n", Perrid.displayname,message]; } self.textBox.text = [Self.textBox.text stringbyappendingstring:finalmessage];} #pragma mark mcbrosercontrollerdelegate-(void) Browserviewcontrollerdidfinish: (Mcbrowserviewcontroller *) browserviewcontroller{[self DISMISSBROWSERVC];} -(void) browserviewcontrollerwascancelled: (Mcbrowserviewcontroller *) browserviewcontroller{[self dismissBrowserVc ];} #pragma mark text Box proxy-(BOOL) Textfieldshouldreturn: (Uitextfield *) textfield{[TextField Resignfirstresponder]; [Self sendText]; return YES;} The session's proxy method listens for data-(void) session: (Mcsession *) session Didreceivedata: (NSData *) data frompeer: (Mcpeerid *) peerid{nsstring *message = [[NSString alloc]initwithdata:data encoding:nsutf8stringencoding]; Dispatch_async (Dispatch_get_main_queue (), ^{[self recivemessage:message frompeer:peerid]; });} Session listener is connected successfully-(void) session: (Mcsession *) session Peer: (Mcpeerid *) Peerid didchangestate: (mcsessionstate) state{
Three. One of the most commonly used corebluetoolth core new Bluetooth technology, also known as Low power
Whether it is Gamekit or multipeerconnectivity is limited to Apple's mobile phone running, very inconvenient. Corebluetooth.framework is based on the BLE4.0 standard, but also can meet other mobile phones, currently used very widely. Use in the market definition, indoor positioning, micro-payment, furniture and other fields. It is also designed in a way that is an opportunity for server and client design patterns. The server side is the peripheral device peripheral, and the client is central.
The following local locationmanage positioning as a central device, peripheral hotspot for other Bluetooth devices to do the relevant instructions
3.1 Define the device designation and name;
Unique identification of the Bluetooth service///32-bit 8-4-4-4-12#define kuuid @ "00000000-0000-0000-0000-000000000000"//Current Bluetooth flag # # Kidentifier @ "Someidentifier" @import corebluetooth; @import corelocation; @interface Viewcontroller () < Cllocationmanagerdelegate, cbperipheralmanagerdelegate>/** Beacon to the outside broadcast */@property (Nonatomic,strong) Cbperipheralmanager *peripheralmanager;/** Beacon Range */@property (nonatomic,strong) clbeaconregion *beaconregion;/** Location Management */@property (Nonatomic,strong) Cllocationmanager *locationmanager; @end
3.2 Request Location Services--need to be aware of the need to determine whether the user agrees to iOS8.0
-(Cllocationmanager *) locationmanager{ if (!_locationmanager) {// iOS8, the location service requires a user license _locationmanager = [Cllocationmanager new]; _locationmanager.delegate = self;//First to determine if there is a method, if any, to execute . if ([_locationmanager respondstoselector: @selector (requestalwaysauthorization)]) {//Request authorization operation, need to modify Info.plist file [ _locationmanager requestalwaysauthorization]; } } return _locationmanager;}
3.3 Proxy method Selective implementations in Locationmanage when entering a zone or exiting a hotspot area
-(void) Locationmanager: (Cllocationmanager *) Manager didexitregion: (clregion *) region{ NSLog (@ "didexitregion Exit an area "); -(void) Locationmanager: (Cllocationmanager *) Manager didenterregion: (clregion *) region{ NSLog (@ "didenterregion Enter an area "); -(void) Locationmanager: (Cllocationmanager *) Manager diddeterminestate: (clregionstate) State forregion: (Clregion *) region{//inside, outside, unknown NSLog (@ "Change of State");} -(void) Locationmanager: (Cllocationmanager *) Manager didrangebeacons: (Nsarray<clbeacon *> *) beacons inregion: ( Clbeaconregion *) region{ NSLog (@ "didrangebeacons learn the distance from Beacon%@", beacons); For (Clbeaconregion *region in beacons) {// can get detailed parameters for each region// proximity This enumeration variable, flag current distance// FAR/near/special near/not found//< C8/>region.proximity }}
3.4 Use Locaitonmanager's proxy method to get all hotspot objects at the current location
-(void) Locationmanager: (Cllocationmanager *) Manager didrangebeacons: (Nsarray<clbeacon *> *) beacons inregion: ( Clbeaconregion *) region{ NSLog (@ "didrangebeacons learn the distance from Beacon%@", beacons); For (Clbeaconregion *region in beacons) {// can get detailed parameters for each region// proximity This enumeration variable, flag current distance// FAR/near/special near/not found//< C5/>region.proximity }} #pragma mark-beacon type-(clbeaconregion *) beaconregion{ if (!_beaconregion) { Nsuuid *proximityuuid=[[nsuuid alloc] initwithuuidstring:kuuid]; _beaconregion = [[Clbeaconregion alloc] Initwithproximityuuid:proximityuuid identifier:kidentifier]; } return _beaconregion;}
3.5 Start to monitor hotspots, stop hot spots, stop detection hotspots, start to detect surrounding hotspots, start broadcasting, stop broadcasting,
Detection-(Ibaction) monterning: (Uisegmentedcontrol *) Sender {if (Sender.selectedsegmentindex = = 0) {[self.location Manager StopMonitoringForRegion:self.beaconRegion]; }else{[Self.locationmanager startMonitoringForRegion:self.beaconRegion]; }}//, ranging range-(ibaction) Location: (Uisegmentedcontrol *) Sender {if (sender.selectedsegmentindex==0) { [Self.locationmanager stopRangingBeaconsInRegion:self.beaconRegion]; }else{[Self.locationmanager startRangingBeaconsInRegion:self.beaconRegion]; }}//Broadcast-(ibaction) Advertise: (Uisegmentedcontrol *) Sender {if (Sender.selectedsegmentindex = = 0) {[_peripheralm Anager stopadvertising]; }else{_peripheralmanager=[[cbperipheralmanager alloc] initwithdelegate:self queue:nil Options:nil]; }}//triggered when broadcast status is updated-(void) Peripheralmanagerdidupdatestate: (Cbperipheralmanager *) peripheral{//if broadcast status is on if (peripheral . state = = Cbperipheralmanagerstatepoweredon) {clbeaconregion *regioN=[[clbeaconregion Alloc] InitWithProximityUUID:self.beaconRegion.proximityUUID major:rand () Minor:rand () Identifier:kidentifier]; [_peripheralmanager startadvertising:[region Peripheraldatawithmeasuredpower:nil]; }}
2.OC bluetooth function