iOS Bluetooth(蓝牙)

1. 蓝牙发送照片
#import "ViewController.h"
#import <GameKit/GameKit.h>

@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, GKPeerPickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

/** 会话类*/
@property (nonatomic, strong) GKSession *session;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

#pragma mark 连接设备
- (IBAction)connectClick:(id)sender {
    //1. 创建GKPeerPickerController连接控制器
    GKPeerPickerController * picker = [GKPeerPickerController new];
    
    //2. 设置代理 --> 获取数据
    picker.delegate = self;
    
    //3. 显示控制器 --> show 此控制器和AlertView很像, 不是全屏的, 不用push modal
    [picker show];
}

#pragma mark GKPeerPickerController 代理方法
/**
 此方法在连接到另一台设备时, 会调用
 peerID: 另一台设备的ID
 session: 会话类, 用于接收和发送数据
 */
- (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
    //1. 保留session
    self.session = session;
    
    //2. 设置句柄 (设置代理) --> 将来一旦受到数据, 将由句柄的方法来处理数据
    // 一旦设置了句柄, 那么还需要实现另一个方法
    [self.session setDataReceiveHandler:self withContext:nil];
    
    //3. 消失控制器
    [picker dismiss];
}

// 一旦设置了句柄, 还需要实现此方法
#pragma mark 接收到数据的时候, 会调用此方法来处理
- (void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context
{
    //1. 将Data转换成image对象
    UIImage *image = [UIImage imageWithData:data];
    
    //2. 然后设置到界面上
    self.imageView.image = image;
}


#pragma mark 发送照片方法
- (IBAction)sendPhotoClick:(id)sender {
    //1. 将image转换成Data
    NSData *data = UIImageJPEGRepresentation(self.imageView.image, 0.5);
    
    //2. 使用会话类发送数据
    /**
     GKSendDataReliable,     如果发送失败, 会重新发送, 直到成功
     GKSendDataUnreliable,   发送一次就不管了
     */
    [self.session sendDataToAllPeers:data withDataMode:GKSendDataReliable error:nil];
}

#pragma mark 选择照片
- (IBAction)selectPhontoClick:(id)sender {
    //1. 判断是否可用
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        return;
    }
    
    //2. 创建UIImagePickerController
    UIImagePickerController *picker = [UIImagePickerController new];
    
    //3. 设置类型
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    //4. 设置代理
    picker.delegate = self;
    
    //5. 模态视图弹出
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark UIImagePickerController 代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //1. 获取照片并显示到界面上
    self.imageView.image = info[UIImagePickerControllerOriginalImage];
    
    //2. 关闭控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
2. CoreBluetooth
#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface ViewController ()<CBCentralManagerDelegate, CBPeripheralDelegate>

/** 中央管理者*/
@property (nonatomic, strong) CBCentralManager *mgr;

/** 扫描到的外围设备的数据数组*/
@property (nonatomic, strong) NSMutableArray *peripheralArray;

@end

@implementation ViewController

- (NSMutableArray *)peripheralArray
{
    if (_peripheralArray == nil) {
        _peripheralArray = [NSMutableArray array];
    }
    return _peripheralArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1. 建立中央管理者
    //queue: 如果传空, 就代表着在主队列
    self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    
    //2. 扫描周边设备
    //Services: 是服务的UUID, 而且是个数据. 如果不穿, 默认扫描全部服务
    [self.mgr scanForPeripheralsWithServices:nil options:nil];
}

#pragma mark - CBCentralManager 代理方法
#pragma mark 必须调用的代理方法
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    
    NSLog(@"state: %zd",central.state);
}

#pragma mark 当发现外围设备时, 会调用的方法
/**
 Peripheral: 外围设备
 Data : 相关的数据
 RSSI : 信号强度
 */
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    //3. 记录扫描到的设备
    if (![self.peripheralArray containsObject:peripheral]) {
        [self.peripheralArray addObject:peripheral];
    }
    
    // 隐藏的步骤: 你应该搞一个列表给用户选择, 让用户自己选择要连接到哪一个设备
}

#pragma mark 连接扫描到的设备 --> 此方法是咱们自己写的, 用户当选中了设备时,应该调用此方法
- (void)connectPeripheral:(CBPeripheral *)peripheral
{
    //4. 连接外围设备
    [self.mgr connectPeripheral:peripheral options:nil];
}

#pragma mark 此方法是连接到外设时会调用的代理方法
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
#warning
    //5. 设置外围设备的代理 --> 一旦连接外设, 那么将有外设来管理服务和特征的处理
    peripheral.delegate = self;
    //6. 扫描服务 --> 可以传入UUID
    // 传空, 代表扫描所有服务
    [peripheral discoverServices:nil];
}

#pragma mark 外设的代理方法 当发现到服务的时候会调用
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    //7. 获取指定的服务, 然后根据此服务来查找特征
    //services : 外设的所有服务, 会保存在一个services中
    for (CBService *service in peripheral.services) {
        //加入我们的服务的UUID是 "123"
        if ([service.UUID.UUIDString isEqualToString:@"123"]) {
            
            //如果UUID一致, 则开始扫描特征
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
    
    
}

#pragma mark 外设的代理方法 当发现到特征的时候会调用
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    //8. 获取指定的特征, 然后根据此特征, 才能根据自己的需求进行数据交互处理
    //char<#(nonnull CBCharacteristic *)#>acteristics : 服务的数组中, 会包含在一个characteristics的数组
    for (CBCharacteristic *characteristic in service.characteristics) {
        //假如我们的特征的UUID是 "456"
        if ([characteristic.UUID.UUIDString isEqualToString:@"456"]) {
            
            // 如果获取到了指定的特征, 则可以进行数据交互处理
           
            //[peripheral readValueForCharacteristic:characteristic];
           // peripheral writeValue:<#(nonnull NSData *)#> forCharacteristic: type:<#(CBCharacteristicWriteType)#>
            
        }
    }
    //
}

#pragma mark 断开连接
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //9. 断开连接
    [self.mgr stopScan];
}

@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值