iOS 蓝牙开发实现文件传输

news/2024/11/25 5:23:46/

  这是一篇旧文,三年前就写过了,一直没有时间分享出来,最近简单整理了下,希望能帮到有需要的人。
  由于我这里没有相关的蓝牙设备,主要用了两个手机,一个作为主设备,一个做为从设备。另外进行蓝牙开发有一个调试利器。
在这里插入图片描述
主设备和从设备我分别创建了一个管理类。
主设备主要进行的操作如下:

  • 开始扫描设备
  • 停止扫描设备
  • 连接设备
  • 断开连接设备
  • 发送数据

具体源码如下:

#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>NS_ASSUME_NONNULL_BEGIN@interface JKBlueToothCenterHelper : NSObject
/// 设备管理者状态block
@property (nonatomic, copy) void(^btStatusBlock)(NSInteger status,NSString *message);
/// 设备连接状态的block
@property (nonatomic, copy) void(^btConnectStatusBlock)(CBPeripheral *peripheral, NSError * _Nullable error);
/// 断开链接block
@property (nonatomic, copy) void(^btDisconnectStatusBlock)(CBPeripheral *peripheral, NSError * _Nullable error);
/// 扫描到的设备列表block
@property (nonatomic,copy) void(^btScanDevicesBlock)(NSMutableArray <CBPeripheral *>*devices);/// 接收到数据的block
@property (nonatomic,copy) void(^receivedDataBlock)(NSData *data, NSError *error);/**开始扫描设备@param services 扫描的服务@param options 扫描的选项配置@param containDefaultService 是否包含默认的服务@return JKBlueToothCenterHelper 对象*/
- (instancetype)initWithScanServices:(nullable NSArray<CBUUID *> *)services options:(nullable NSDictionary <NSString *, id> *)options containDefaultService:(BOOL)containDefaultService;/**
扫描设备*/
- (void)scanDevice;/**停止扫描设备*/
- (void)stopScanDevice;/**连接设备@param peripheral 设备@param options 配置信息*/
- (void)connectToDevice:(CBPeripheral *)peripheral options:(NSDictionary <NSString *, id> *)options;/**断开连接设备@param peripheral 设备*/
- (void)disconnectToDevice:(CBPeripheral *)peripheral;/**设备管理者向设备发送数据@param data 二进制数据@param peripheral 接受数据的设备@param CBCharacteristic 特征@param type 请求类型*/
- (void)sendData:(NSData *)data toPeripheral:(CBPeripheral *)peripheral forCharacteristic:(CBCharacteristic *)CBCharacteristic type:(CBCharacteristicWriteType)type complete:(void(^)(NSError *error))completeBlock;@endNS_ASSUME_NONNULL_END
typedef void(^JKBTCenterSendCompleteBlock)(NSError *error);@interface JKBlueToothCenterHelper()<CBCentralManagerDelegate,CBPeripheralDelegate>@property (nonatomic, strong) CBCentralManager  *centerManager; ///< 管理者
@property (nonatomic, strong) NSMutableArray *scanServices;            ///< 扫描的服务
@property (nonatomic, strong) NSDictionary <NSString *, id>      *scanOptions; ///< 扫描的配置
@property (nonatomic,strong) NSMutableArray *scannedDevices; ///< s扫描到的设备
@property (strong , nonatomic) CBPeripheral * discoveredPeripheral;//周边设备
@property (nonatomic,copy) JKBTCenterSendCompleteBlock sendCompleteBlock;@end@implementation JKBlueToothCenterHelper
- (instancetype)initWithScanServices:(nullable NSArray<CBUUID *> *)services options:(nullable NSDictionary <NSString *, id> *)options containDefaultService:(BOOL)containDefaultService{self = [super init];if (self) {[self.scanServices addObjectsFromArray:services];if (containDefaultService) {[self setupDefalutScanService];}self.scanOptions = options;[self centerManager];}return self;
}- (void)setupDefalutScanService{CBUUID *uuid = [CBUUID UUIDWithString:DEFAULT_SERVICE_UUID];[self.scanServices addObject:uuid];}- (void)scanDevice{[self.scannedDevices removeAllObjects];[self.centerManager scanForPeripheralsWithServices:self.scanServices options:self.scanOptions];
}- (void)stopScanDevice{[self.centerManager stopScan];
}- (void)connectToDevice:(CBPeripheral *)peripheral options:(NSDictionary <NSString *, id> *)options{self.discoveredPeripheral = peripheral;self.discoveredPeripheral.delegate = self;[self.centerManager connectPeripheral:peripheral options:options];
}- (void)disconnectToDevice:(CBPeripheral *)peripheral{[self.centerManager cancelPeripheralConnection:peripheral];
}- (void)sendData:(NSData *)data toPeripheral:(CBPeripheral *)peripheral forCharacteristic:(CBCharacteristic *)CBCharacteristic type:(CBCharacteristicWriteType)type complete:(void(^)(NSError *error))completeBlock{self.sendCompleteBlock = completeBlock;[peripheral writeValue:data forCharacteristic:CBCharacteristic type:type];
}#pragma mark - - - - CBCentralManagerDelegate - - - -
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{if (@available(iOS 10.0, *)) {switch (central.state) {case CBManagerStatePoweredOn://蓝牙打开{[self.centerManager scanForPeripheralsWithServices:self.scanServices options:self.scanOptions];}break;case CBManagerStatePoweredOff://蓝牙关闭了{if (self.btStatusBlock) {self.btStatusBlock(CBManagerStatePoweredOff, @"蓝牙已关闭,请打开蓝牙");}}break;case CBManagerStateUnsupported://不支持{if (self.btStatusBlock) {self.btStatusBlock(CBManagerStatePoweredOff, @"蓝牙设备不支持!");}}break;default:break;}} else {// Fallback on earlier versionsswitch (central.state) {case 5://蓝牙打开{[self.centerManager scanForPeripheralsWithServices:self.scanServices options:self.scanOptions];}break;case 4://蓝牙关闭了{if (self.btStatusBlock) {self.btStatusBlock(4, @"蓝牙已关闭,请打开蓝牙");}}break;case 2://不支持{if (self.btStatusBlock) {self.btStatusBlock(2, @"蓝牙设备不支持!");}}break;default:break;}}}- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{if (!peripheral) {return;}[peripheral discoverServices:self.scanServices];if (![self.scannedDevices containsObject:peripheral]) {[self.scannedDevices addObject:peripheral];if (self.btScanDevicesBlock) {self.btScanDevicesBlock(self.scannedDevices);}}}- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(nonnull CBPeripheral *)peripheral error:(nullable NSError *)error{if (self.btConnectStatusBlock) {self.btConnectStatusBlock(peripheral, error);}
}- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{if (@available(iOS 9.0, *)) {if (self.centerManager.isScanning) {[self stopScanDevice];}} else {// Fallback on earlier versions[self stopScanDevice];}self.discoveredPeripheral = peripheral;[peripheral setDelegate:self];[peripheral discoverServices:nil];if (self.btConnectStatusBlock) {self.btConnectStatusBlock(peripheral, nil);}
}- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(nonnull CBPeripheral *)peripheral error:(nullable NSError *)error{if (self.btDisconnectStatusBlock) {self.btDisconnectStatusBlock(peripheral, error);}
}//- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *, id> *)dict{
//    
//}#pragma mark - - - - CBPeripheralDelegate - - - -
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error{peripheral.delegate = self;NSArray *services = peripheral.services;for (CBService *service in services) {[peripheral discoverCharacteristics:nil forService:service];}
}- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error{for (CBCharacteristic *characteristic in service.characteristics) {if ([[NSString stringWithFormat:@"%@",characteristic.UUID] isEqualToString: DEFAULT_CHARACTERISTIC_UUID]) {[self.discoveredPeripheral setNotifyValue:YES forCharacteristic:characteristic];}}}// 写入成功
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error {if (self.sendCompleteBlock) {self.sendCompleteBlock(error);}
}-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {if (error) {//NSLog(@"订阅失败");//NSLog(@"%@",error);}if (characteristic.isNotifying) {//NSLog(@"订阅成功");} else {//NSLog(@"取消订阅");}
}- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{[peripheral readValueForCharacteristic:characteristic];NSData *data = characteristic.value;if (self.receivedDataBlock) {self.receivedDataBlock(data,error);}
}#pragma mark - - - - lazyLoad - - - -
- (CBCentralManager *)centerManager{if (!_centerManager) {dispatch_queue_t queue = dispatch_queue_create("com.btCenterManager.queue", 0);CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:queue options:nil];centralManager.delegate = self;_centerManager = centralManager;}return _centerManager;
}- (NSMutableArray *)scannedDevices{if (!_scannedDevices) {_scannedDevices = [NSMutableArray new];}return _scannedDevices;
}- (NSMutableArray *)scanServices{if (!_scanServices) {_scanServices = [NSMutableArray new];}return _scanServices;
}@end

从设备进行的操作如下:

  • 添加服务
  • 开始广播
  • 停止广播
  • 发送数据
    具体源码如下:
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>typedef void(^JKBTPeripheralStatusBlock)(NSInteger status,NSString *message);
typedef void(^JKBTPeripheralRecievedDataBlock)(NSData *data,NSError *error);@interface JKBlueToothPeripheralHelper : NSObject@property (nonatomic,copy) JKBTPeripheralStatusBlock btStatusBlock;///< 蓝牙状态的block
@property (nonatomic,copy) JKBTPeripheralRecievedDataBlock receivedDataBlock;/**初始化JKBlueToothPeripheralHelper 对象@param services 提供的服务数组@param adContent 广播内容*/
- (void)addServices:(NSArray <CBMutableService *>*)services adContent:(NSDictionary *)adContent;/**添加默认的服务*/
- (void)addDefaultService;/**开始广播*/
- (void)startAdvertising;/**停止广播*/
- (void)stopAdvertising;/**
发送数据到设备管理器@param data 二进制数据@param centerDevices 主设备@param characteristic 特征*/
- (void)sendData:(NSData *)data toCenterManagers:(NSArray <CBCentral*>*)centerDevices forCharacteristic:(CBMutableCharacteristic *)characteristic;@end
#import "JKBlueToothPeripheralHelper.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import <UIKit/UIKit.h>
#import "JKBlueToothMacro.h"
@interface JKBlueToothPeripheralHelper()<CBPeripheralManagerDelegate>
@property (nonatomic,strong)CBPeripheralManager *peripheralManager;
@property (nonatomic,strong) NSDictionary *adContent;        ///< 广播内容
@property (nonatomic,strong) CBMutableService *defaultService; ///< 默认提供的服务
@property (nonatomic,strong) CBMutableCharacteristic *defaultCharacteristic; ///< 默认具有的特征
@property (nonatomic,strong) NSMutableArray <CBMutableService *>*services;
@property (nonatomic,strong) NSMutableArray <CBCentral *>*centrals;
@end@implementation JKBlueToothPeripheralHelper- (void)addServices:(NSArray <CBMutableService *>*)services adContent:(NSDictionary *)adContent{if (!self.peripheralManager) {dispatch_queue_t queue = dispatch_queue_create("com.btPeripheralManager.queue", 0);self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:queue];}if (services.count>0) {[self.services addObjectsFromArray:services];}self.adContent = adContent;}- (void)addDefaultService{CBUUID *serviceID = [CBUUID UUIDWithString:DEFAULT_SERVICE_UUID];CBMutableService *service = [[CBMutableService alloc] initWithType:serviceID primary:YES];// 创建服务中的特征CBUUID *characteristicID = [CBUUID UUIDWithString:DEFAULT_CHARACTERISTIC_UUID];CBMutableCharacteristic *characteristic = [[CBMutableCharacteristic alloc]initWithType:characteristicIDproperties:CBCharacteristicPropertyRead |CBCharacteristicPropertyWrite |CBCharacteristicPropertyNotifyvalue:nilpermissions:CBAttributePermissionsReadable |CBAttributePermissionsWriteable];// 特征添加进服务[JKBlueToothModule service:service addCharacteristic:characteristic];self.defaultCharacteristic = characteristic;self.defaultService = service;[self.services addObject:self.defaultService];
}- (void)startAdvertising{[self.peripheralManager startAdvertising:self.adContent];
}- (void)stopAdvertising{[self.peripheralManager stopAdvertising];
}- (void)sendData:(NSData *)data toCenterManagers:(NSArray <CBCentral*>*)centerDevices forCharacteristic:(CBMutableCharacteristic *)characteristic{characteristic = characteristic?:self.defaultCharacteristic;if (!centerDevices || centerDevices.count == 0) {centerDevices = self.centrals;}[self.peripheralManager updateValue:data forCharacteristic:characteristic onSubscribedCentrals:centerDevices];
}#pragma mark - - - - CBPeripheralManagerDelegate - - - -
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{if (@available(iOS 10.0, *)) {switch (peripheral.state) {case CBManagerStatePoweredOn://蓝牙打开{for (CBMutableService *service in self.services) {[self.peripheralManager addService:service];}[self startAdvertising];}break;case CBManagerStatePoweredOff://蓝牙关闭了{if (self.btStatusBlock) {self.btStatusBlock(CBManagerStatePoweredOff, @"蓝牙已关闭,请打开蓝牙");}}break;case CBManagerStateUnsupported://不支持{if (self.btStatusBlock) {self.btStatusBlock(CBManagerStatePoweredOff, @"蓝牙设备不支持!");}}break;default:break;}} else {// Fallback on earlier versionsswitch (peripheral.state) {case 5://蓝牙打开{for (CBMutableService *service in self.services) {[self.peripheralManager addService:service];}[self startAdvertising];}break;case 4://蓝牙关闭了{if (self.btStatusBlock) {self.btStatusBlock(4, @"蓝牙已关闭,请打开蓝牙");}}break;case 2://不支持{if (self.btStatusBlock) {self.btStatusBlock(2, @"蓝牙设备不支持!");}}break;default:break;}}
}-(void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{}- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request{
//    if (request.characteristic.properties & CBCharacteristicPropertyRead) {
//        NSData *data = request.characteristic.value;
//       // [request setValue:data];
//        //[self.peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
//    } else {
//        [self.peripheralManager respondToRequest:request withResult:CBATTErrorReadNotPermitted];
//    }}- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests {CBATTRequest *request = requests.lastObject;if (request.characteristic.properties & CBCharacteristicPropertyWrite) {CBMutableCharacteristic *characteristic = (CBMutableCharacteristic *)request.characteristic;characteristic.value = request.value;if (self.receivedDataBlock) {self.receivedDataBlock(request.value,nil);}[self.peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];} else {if (self.receivedDataBlock) {NSError *error = [[NSError alloc] initWithDomain:@"JKBlueToothModule" code:CBATTErrorWriteNotPermitted userInfo:@{@"msg":@"CBATTErrorWriteNotPermitted error"}];self.receivedDataBlock(nil,error);}[self.peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted];}
}//订阅characteristics
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{//NSLog(@"订阅了 %@的数据",characteristic.UUID);[self.centrals addObject:central];}//取消订阅characteristics
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic{//NSLog(@"取消订阅 %@的数据",characteristic.UUID);[self.centrals removeObject:central];}#pragma mark - - - - lazyLoad - - - -
- (NSMutableArray *)services{if (!_services) {_services  = [NSMutableArray new];}return _services;
}- (NSMutableArray *)centrals{if (!_centrals) {_centrals = [NSMutableArray new];}return _centrals;
}@end

代码可以直接复制直接使用。由于我这边是私有库,就不开放给大家了。另外文件传输时,参考我之前写的一篇文章《iOS蓝牙开发之数据传输精华篇》
里面有讲到数据拼接的一个工具 ,pod集成如下:

pod 'JKTransferDataHelper'

这里写图片描述


http://www.ppmy.cn/news/773038.html

相关文章

Ubuntu蓝牙Bluetooth命令行连接发送文件完整流程

1.确保bluez已安装好 $sudo apt install bluez 2.查看当前蓝牙阻塞状态 $sudo rfkill list 如果上面阻塞状态为yes,表示蓝牙关闭,则需要unblock打开蓝牙&#xff1a; $sudo rfkill unblock bluetooth 3.执行bluetoothctl $bluetoothctl 4.扫描其他蓝牙设备 $scan on 5.…

计算机如何用蓝牙实现文件传输,Win10系统电脑通过蓝牙进行传输文件操作步骤...

Win10系统如何使用蓝牙传输文件&#xff1f;相信用过win10系统的用户都知道&#xff0c;win10系统当中的蓝牙功能可以用来连接蓝牙耳机&#xff0c;蓝夜鼠标等设备。但其实&#xff0c;win10系统当中的蓝牙也可以用来传输文件&#xff0c;只需要用蓝牙将电脑与手机连接起来&…

linux蓝牙传送的文件存放,嵌入式蓝牙文件传送方案的实现

蓝牙是一种低成本、短距离无线通信技术&#xff0c;工作频段使用全球统一开放的2.4 GHz的ISM频段[1]&#xff0c;并将此频段分为79个跳频点&#xff0c;采用跳频技术&#xff0c;增强了蓝牙通信的可靠性。蓝牙技术现已被广泛应用于无线通信领域中&#xff0c;如个人无线通信设备…

android+蓝牙传输文件,在Android中使用蓝牙的消息和文件传输

我正在开发一个应用程序,首先我们必须搜索和连接可用的配对蓝牙设备.我做到了连接.但之后我放了一个屏幕要求在文本和文件传输之间进行选择.当我选择文本时,将打开另一个屏幕,其中有edittext和按钮.无论用户在edittext中输入什么,点击按钮,都应该转移到BT聊天应用程序等连接的B…

android 12系统蓝牙传输大文件比较慢

1&#xff0c;修改蓝牙的波特率 这个改3000000能提高一点速度,蓝牙本来速度都很慢,最多也就200k左右速度 diff --git a/hardware/broadcom/libbt/include/vnd_rksdk.txt b/hardware/broadcom/libbt/include/vnd_rksdk.txt index d2d93fe48b0…af6c1662b77 100755 — a/hardwa…

android蓝牙传文件在哪里找,手机蓝牙传输的文件在哪里_华为手机蓝牙传输记录在哪-系统城...

蓝牙传输是无线传输的一种&#xff0c;在没网时很多用户都会选择用蓝牙来传输&#xff0c;但手机蓝牙传输的文件在哪里呢&#xff1f;有些使用华为手机的用户就有这一疑问&#xff0c;所以对此今天本文为大家分享的就是关于华为手机蓝牙传输记录的查看方法。 查看方法如下&…

android蓝牙传文件开发,Android Bluetooth文件传输

【实例简介】 Android Bluetooth文件的引入和传输,可使用两台设备,一个做客户端一个做服务端,传输文件,显示传送进度。 【实例截图】 【核心代码】 Bluetooth └── Bluetooth ├── AndroidManifest.xml ├── bin │ ├── AndroidManifest.xml │ └── classe…

两台电脑用蓝牙传文件出现“系统资源不足,电脑之间互相传递单个大文件,例如单个文件50g,100g

两台电脑用蓝牙传文件出现“系统资源不足,电脑之间互相传递单个大文件&#xff0c;例如单个文件50g,100g 1.我的使用场景是这样的&#xff0c;有一个50g的文件要从一台电脑传输到另一台电脑上&#xff0c;想起了无线传输 中的蓝牙进行传输&#xff0c;尝试了几次,弹窗提示&…