IOS Bluetooth and ios Bluetooth

Source: Internet
Author: User

IOS Bluetooth and ios Bluetooth

# Bluetooth ## GameKit ### introduction: * For 'communication' between bluetooth devices, you can only use the 'same application' connection between iOS devices * The connection has expired since 'ios7 '* But GameKit is 'basic the 'bluetooth communication framework * enables file sharing through Bluetooth (only files in the device sandbox) * This framework is generally used for game development (for example, playing the game with five games) ## start case ### introduction: * connect two iOS devices through Bluetooth * search for the device of the other party * to send images from the mobile phone to the other party ### build the interface ### Bluetooth Interconnection: * search for the bluetooth device ''' // initialize the link to the Bluetooth controller GKPeerPickerController * peerCtr = [[GKPeerPickerController alloc] init]; // display the matching bluetooth device [peerCtr show]; ''' * 'gpeerpickercontroller' two most important proxies '''/*** link successful ** @ Param picker Bluetooth controller * @ param peerID the device id connecting to Bluetooth * @ param session connects to a Bluetooth session (Communication) for data transmission */-(void) peerPickerController :( GKPeerPickerController *) picker didConnectPeer :( NSString *) peerID toSession :( GKSession *) session {NSLog (@ "% s % d" ,__ func __,__ LINE __); // hide the Bluetooth controller [picker dismiss];} // exit connection-(void) peerPickerControllerDidCancel :( GKPeerPickerController *) picker {NSLog (@ "% s % d" ,__ func __, __line _);} ''' ### select an image :* Select image method ''' // select image-(IBAction) chooseImage {// 1. initialize the image and select the Controller UIImagePickerController * imgPicker = [[UIImagePickerController alloc] init]; // 2. determine whether the image library is available if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {// 3. set the image library open type imgPicker. sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; // 4. sets the proxy imgPicker. delegate = self; // 5. open gallery [self pr EsentViewController: imgPicker animated: YES completion: nil] ;}} ''' * select the proxy method of the image controller '''/*** image selection complete call ** @ param picker Image Selection controller * @ param info selected information */-( void) imagePickerController :( UIImagePickerController *) picker didFinishPickingMediaWithInfo :( NSDictionary <NSString *, id> *) info {NSLog (@ "info =%@", info ); // set the selected image to the current display image self. showImageView. image = info [UIImagePickerControllerOriginalImage]; // hide the current Select the image controller [picker dismissViewControllerAnimated: YES completion: nil];} ''' ### send images to each other: * You need to store the current session ''' in the proxy method of successful connection // Save the current session self. m_Session = session; ''' * method of sending an image ''' // send an image-(IBAction) sendImage {// obtain the image UIImage * image = self. showImageView. image; // convert the image to NSData type NSData * imgData = UIImagePNGRepresentation (image ); /*** send data to all matched users ** @ param GKSendDataMode: (safe/insecure) * GKSendDataUnreliable: Unsafe mode: Like sending 10 leaflets and dropping leaflets to the crowd, whether or not you can receive them, regardless of * GKSendDataReliable: Safe Mode: Like sending 10 leaflets, each leaflet must be sent to passers-by's hand before a leaflet is issued * @ return */[self. m_Session sendDataToAllPeers: imgData withDataMode: GKSendDataUnreliable error: nil];} ''' ### set the image: * The data accepted by GameKit is a method callback * You need to listen to the received data * set the listener '''/** in the proxy method for successful connection * setDataReceiveHandler: * withContext: the parameter to be passed in the listener */[session setDataReceiveHandler: self withContext: ni L]; ''' * listener Method * only sets who listens for the transmitted data, because we still cannot get the transmitted data, enter the header file of the listening method and you will see ''' // SEL =-receiveData: fromPeer: inSession: context: ''' *. Therefore, we must implement this method to obtain the received data, this callback method is explained in versions earlier than Xcode 7! [] (Clip/callback example .png) '''/*** callback Method for receiving data ** @ param data received data * @ param peer device ID for transmitting data * @ param session current session * @ param context registers the data transmitted by the listener */-(void) receiveData :( NSData *) data fromPeer :( NSString *) peer inSession: (GKSession *) session context :( void *) context {// because the image is passed, therefore, we directly use UIImage to accept UIImage * image = [UIImage imageWithData: data]; // set image self. showImageView. image = image ;}'''
# CoreBlueTooth ### Introduction: * It Can Be Used for third-party bluetooth device interaction, the device must support Bluetooth 4.0 * the iPhone device must be 4S or * The iPad device must be iPad mini or * the iOS system must be iOS 6 or * the Bluetooth 4.0 must be 'lower' famous, therefore, it is generally called BLE (bluetooth low energy) * use simulator debugging-Xcode 4.6-iOS 6.1 * Application Scenario + sports bracelet + Smart Home + lacala Bluetooth card reader ### core concept * CBCentralManager: central device (Butler used to connect to external devices) * CBPeripheralManager: External Device (third-party Bluetooth 4.0 device )! [] (Clip/BLE.jpeg) ### development step * create a central manager ''' // 1. create a central manager and set proxy self. cmgr = [[CBCentralManager alloc] initWithDelegate: self queue: nil]; ''' * scan peripherals (discover) ''' // 2. scan external devices in the proxy method/*** scanForPeripheralsWithServices: if the specified array is input, only devices with corresponding IDs in the array will be scanned * If nil is input, scan all the discovered devices * after scanning the external devices, the proxy */-(void) centralManagerDidUpdateState (CBCentralManager *) will be notified *) central {if ([central state] = CBCentralManagerState PoweredOn) {[self. cmgr scanForPeripheralsWithServices: nil options: nil] ;}}'''/*** external device discovery, this method is called every time a scan is found * so you can use an array to store the array completed each scan */-(void) centralManager :( CBCentralManager *) central didDiscoverPeripheral :( CBPeripheral *) peripheral advertisementData :( NSDictionary <NSString *, id> *) advertisementData (NSNumber *) RSSI {// may cause repeated scanning peripherals. // you must first determine whether the array contains this peripheral if (! [Self. peripherals containsObject: peripheral]) {[self. peripherals addObject: peripheral];} ''' * connect to peripherals '''/*** simulate the start connection method */-(void) start {// 3. connect the peripheral for (CBPeripheral * ppl in self. peripherals) {// scan the peripheral service // this operation should be performed by the proxy method of the peripheral device. // set the proxy ppl. delegate = self; [self. cmgr connectPeripheral: ppl options: nil] ;}} ''' * scan for services and features in peripherals-Relationship between services and features. Each Bluetooth 4.0 device displays its own services and features, A device must contain one or more services. Each Service contains several features. '''/*** Call peripherals successfully */-(void) centralManager :( CBCentralManager *) central didConnectPeripheral :( CBPeripheral *) peripheral {// query peripheral services [peripheral discoverServices: nil];} '''/*** the proxy method is called when the service is found. ** @ param peripheral peripherals */-(void) peripheral :( CBPeripheral *) peripheral didDiscoverServices :( NSError *) error {// scan all services of the device NSArray * services = peripheral. services; // scan the corresponding features of each service again based on the service. for (CBService * ses in services) {[peripheral discoverCharacteristics: nil forService: ses];} ''' * Data Interaction with peripherals-perform corresponding operations under the specified features '''/*** discover the characteristics of the Service */-(void) peripheral :( CBPeripheral *) peripheral didDiscoverCharacteristicsForService :( CBService *) service error :( NSError *) error {// feature NSArray * ctcs = service corresponding to the service. characteristics; // traverses all features for (CBCharacteristic * character in ctcs) {// filter if ([character. UUID. UUIDString isEqualToString: @ "XMG"]) {NSLog (@ "you can eat ");}}} ''' * disconnect '''/*** disconnect */-(void) stop {// disconnect all peripherals on the connection for (CBPeripheral * per in self. peripherals) {[self. cmgr cancelPeripheralConnection: per];} '''

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.