iOSBluetooth(藍芽)

凌浩雨發表於2018-01-25

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


相關文章