蓝牙BLE – IOS开发

IOS制作类似Android的Toast功能

  • Toast.h
  • #import 
    #import 
    @interface TopToast : NSObject
    // API
    + (void)showToptoastWithText:(NSString *)text;
    + (void)showToptoastWithText:(NSString *)text duration:(CGFloat)duration;
    + (void)showToptoastWithText:(NSString *)text duration:(CGFloat)duration height:(float)height;
    + (void)showToptoastWithText:(NSString *)text duration:(CGFloat)duration height:(float)height backGroundColor:(UIColor *)color;
    + (void)showToptoastWithText:(NSString *)text duration:(CGFloat)duration height:(float)height backGroundColor:(UIColor *)color alpha:(float)alpha;
    @end
    

    @interface、@protocal和@implementation
    在Java中interface是接口、class是类.
    例如如下

    interface BaseInterface {
        void print();
    };
    
    class BaseObject {
        
    };
    

    两者可以通过implement继承

    class BaseObject implement BaseInterface {
        void print() {
            system.out.println("HelloWorld");
        }
    };
    

    那么在OC中是什么情况呢?
    1 @protocal相当于Java的interface
    2 @interface和@implementation两者结合相当于Java中的class
    OC中类包括interface和implementation两个部分
    成员变量和成员方法的声明放置interface部分中
    成员变量和成员方法的实现放置implementation部分中

  • Toast.m
  • #import "TopToast.h"
    #define ToastDispalyDuration 2.0f
    #define ToastBackgroundColor [UIColor purpleColor]
    #define ToastHeight 64
    //
    @interface TopToast ()
    @property (nonatomic, strong) UIButton *contentView;
    @property (nonatomic, assign) CGFloat duration;
    @property (nonatomic, assign) CGFloat height;
    @end
    // 实现
    @implementation TopToast
    //多次点击缓存,逐个显示
    static NSMutableArray *_toastArr;
    - (void)dealloc{
    }
    
    - (id)initWithText:(NSString *)text{
        if (self = [super init]) {
            _duration = ToastDispalyDuration;
            _height = ToastHeight;
            if (_toastArr.count == 0) {
                _toastArr = [[NSMutableArray alloc]init];
            }
            
            _contentView = [[UIButton alloc] initWithFrame:CGRectMake(0, -_height, [UIScreen mainScreen].bounds.size.width, _height)];
            _contentView.backgroundColor = ToastBackgroundColor;
            [_contentView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hide)]];
    
            UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, _height)];
            textLabel.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, _height);
            textLabel.backgroundColor = [UIColor clearColor];
            textLabel.textColor = [UIColor whiteColor];
            textLabel.textAlignment = NSTextAlignmentCenter;
            textLabel.font = [UIFont boldSystemFontOfSize:15];
            textLabel.text = text;
            textLabel.numberOfLines = 0;
            [_contentView addSubview:textLabel];
     
        }
        return self;
    }
    //设置停留时间
    - (void)setDuration:(CGFloat)duration{
        _duration = duration;
    }
    //设置背景色
    - (void)setBackgroundColor:(UIColor *)color{
        _contentView.backgroundColor = color;
    }
    //设置高度
    - (void)setHeigh:(float)height{
        _height = height;
    }
    //设置透明度
    - (void)setBackgroundAlpha:(float)alpha{
        _contentView.alpha = alpha;
    }
    //出现动画
    -(void)showAnimationWithToast:(TopToast *)toast{
        [UIView beginAnimations:@"show" context:NULL];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
        [UIView setAnimationDuration:0.3];
        toast.contentView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, toast.height);
        [UIView commitAnimations];
    }
    //影藏动画
    -(void)hideAnimationWithToast:(TopToast *)toast{
        [UIView animateWithDuration:0.3 animations:^{
            toast.contentView.frame = CGRectMake(0, -toast.height, [UIScreen mainScreen].bounds.size.width, toast.height);
        } completion:^(BOOL finished) {
            [toast.contentView removeFromSuperview];
            //影藏后检查是否有toast缓存
            if (_toastArr.count > 0) {
                [_toastArr removeObjectAtIndex:0];
                if (_toastArr.count > 0) {
                    [self showWithToast:_toastArr[0]];
                }
            }
        }];
    }
    //触摸隐藏
    - (void)hide{
        [UIView animateWithDuration:0.3 animations:^{
            _contentView.frame = CGRectMake(0, -_height, [UIScreen mainScreen].bounds.size.width, _height);
        }completion:^(BOOL finished) {
            [_contentView removeFromSuperview];
        }];
    }
    
    - (void)showWithToast:(TopToast *)toast{
        [[UIApplication sharedApplication].keyWindow addSubview:toast.contentView];
        [self showAnimationWithToast:toast];
        
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_duration * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self hideAnimationWithToast:toast];
        });
    }
    
    + (void)showToptoastWithText:(NSString *)text{
        TopToast *toast = [[TopToast alloc] initWithText:text];
        [toast setDuration:ToastDispalyDuration];
        if (_toastArr.count == 0) {
            [toast showWithToast:toast];
        }
        [_toastArr addObject:toast];
    }
    + (void)showToptoastWithText:(NSString *)text duration:(CGFloat)duration{
        TopToast *toast = [[TopToast alloc] initWithText:text];
        if (_toastArr.count == 0) {
            [toast showWithToast:toast];
        }
        [_toastArr addObject:toast];
    }
    + (void)showToptoastWithText:(NSString *)text duration:(CGFloat)duration height:(float)height{
        TopToast *toast = [[TopToast alloc] initWithText:text];
        [toast setDuration:duration];
        [toast setHeigh:height];
        if (_toastArr.count == 0) {
            [toast showWithToast:toast];
        }
        [_toastArr addObject:toast];
    }
    + (void)showToptoastWithText:(NSString *)text duration:(CGFloat)duration height:(float)height backGroundColor:(UIColor *)color{
        TopToast *toast = [[TopToast alloc] initWithText:text];
        [toast setDuration:duration];
        [toast setHeigh:height];
        [toast setBackgroundColor:color];
        if (_toastArr.count == 0) {
            [toast showWithToast:toast];
        }
        [_toastArr addObject:toast];
    }
    + (void)showToptoastWithText:(NSString *)text duration:(CGFloat)duration height:(float)height backGroundColor:(UIColor *)color alpha:(float)alpha{
        TopToast *toast = [[TopToast alloc] initWithText:text];
        [toast setDuration:duration];
        [toast setHeigh:height];
        [toast setBackgroundColor:color];
        [toast setBackgroundAlpha:alpha];
        
        if (_toastArr.count == 0) {
            [toast showWithToast:toast];
        }
        [_toastArr addObject:toast];
        
    }
    @end
    

    蓝牙BLE4.0开发流程

    1 建立中心角色 (硬件盒子)

    #import 
    CBCentralManager *manager;
    manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    

    2 扫描外设 (外设指的是你的IPhone和IPad)

    [manager scanForPeripheralsWithServices:nil options:options];
    

    3 连接外设
    指的是手机设备和硬件连接过程

    - (void)centralManager:(CBCentralManager*)central didDiscoverPeripheral:(CBPeripheral*)peripheral advertisementData:(NSDictionary*)advertisementData RSSI:(NSNumber*)RSSI {
        if ([peripheral.name isEqualToString:BLE_SERVICE_NAME]) {
            [self connect:peripheral];
        }
    }
    - (BOOL)connect:(CBPeripheral*) peripheral {
        self.manager.delegate = self;
        [self.manager connectPeripheral:peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
    }
    

    4 扫描外设中的服务和特征

    - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
        [peripheral setDelegate:self];
        [peripheral discoverServices:nil];
    }
    
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
        if (error) {
            NSLog(@"Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
            if ([self.delegate respondsToSelector:@selector(DidNotifyFailConnectService:withPeripheral:error:)])
                [self.delegate DidNotifyFailConnectService:nil withPeripheral:nil error:nil];
            return; 
        }
        for (CBService *service in peripheral.services) {
            // 发现服务
            if ([service.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_PROPRIETARY_SERVICE]]) {
                NSLog(@"Service found with UUID: %@", service.UUID);    // 查找特征
                [peripheral discoverCharacteristics:nil forService:service];
                break; 
            }
        }
    }
    
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
        if (error) {
            NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
            [self error];
            return;
        }
        NSLog(@"服务:%@",service.UUID);
        for (CBCharacteristic *characteristic in service.characteristics) {
            //发现特征
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"xxxxxxx"]]) {
                NSLog(@"监听:%@",characteristic); //监听特征
                [self.peripheral setNotifyValue:YES forCharacteristic:characteristic];
            }
        }
    }
    

    5 与外设做数据交互,包括读和写

  • 读操作
  • - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
        if (error) {
            NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, [error localizedDescription]);
            self.error_b = BluetoothError_System;
            [self error];
            return;
        }
        [self decodeData:characteristic.value];
    }
    
  • 写操作
  • NSData *d2 = [[PBABluetoothDecode sharedManager] HexStringToNSData:@"0x02"];
    [self.peripheral writeValue:d2 forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
    

    欢迎留言

    avatar
      Subscribe  
    Notify of