美文网首页
iBeacon-微信摇一摇周边

iBeacon-微信摇一摇周边

作者: 阿龍飛 | 来源:发表于2016-12-31 13:21 被阅读183次

    后台运行蓝牙服务http://www.tuicool.com/articles/n22ea2V

    iBeacon学习http://www.jianshu.com/p/a502eae7b50a

    iOS蓝牙开发之iBeaconhttp://www.jianshu.com/p/1207c8727889

    iOS之蓝牙4.0 BLE相关http://www.jianshu.com/p/0a80e10bf0fc

    iBeacon--- 是苹果公司2013年9月发布的移动设备用OS(iOS7)上配备的新功能。其工作方式是,配备有 低功耗蓝牙(BLE)通信功能的设备使用BLE技术向周围发送自己特有的ID,接收到该ID的应用软件会根据该ID采取一些行动。

    监听ibeacon设备:根据proximityUUID、major 和 minor不同来区分不同的用户再请求协议拿到用户信息在把ID信息显示出来再根据ID查找具体的信息内容

    这个场景是指当你走到商家门前时,你开启蓝牙,并用微信摇一摇周边,那么你可以摇到优惠券和广告等信息。这在O2O领域是应用最广泛的。
    微信摇一摇周边是基于iBeacon来实现的。
    首先要有一个iBeacon硬件(newbeacon)和一部蓝牙4.0以及ios7以上或安卓4.3以上系统的手机。(会有一个专门部署iBeacon基站的APP)
    1.申请微信公众号。服务提供者向微信后台申请服务,微信后台生成一个iBeaconID,并将其映射到服务提供者提供的服务,再将iBeaconID告诉服务提供者;
    2.服务提供者把第一步拿到的iBeaconID设置到iBeacon设备上,让iBeacon设备广播该iBeaconID;
    3.用户在该iBeacon设备的信号范围内打开微信摇一摇周边,微信App拿到该iBeaconID;
    4.微信通过第三步拿到的iBeaconID,向微信后台拉取相应的服务,展示在摇出来的结果上;
    5.用户点击摇出来结果,在微信内嵌的浏览器上,会带上用户信息跳转到服务提供者在第一步申请服务时填的url,进入应用页面。

    CoreBluetooth

    在CoreBluetooth中,蓝牙传输都分为两个部分:

    外围设备CBPeripheral:
    负责发布并广播服务,告诉周围的中央设备它的可用服务和特征,类似于网络通信中的服务端。
    中央设备CBCentral:
    负责和外围设备建立连接,一旦连接成功就可以使用外围设备的服务和特征,类似于网络通信中的客户端

    //
    //  OneViewController.m
    //  text
    //
    //  Created by Monster DD Imac on 17/3/11.
    //  Copyright © 2017年 Monster DD Imac. All rights reserved.
    //
    
    #import "OneViewController.h"
    #import <CoreBluetooth/CoreBluetooth.h>
    #import <AVFoundation/AVFoundation.h>
    #import <AudioToolbox/AudioToolbox.h>
    @interface OneViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>
    
    @property(nonatomic,strong) CBCentralManager *centralManager;
    @property(nonatomic,strong) CBPeripheral *peripheral;
    
    @end
    
    @implementation OneViewController{
        UILabel * lab;
    }
    
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        self.view.backgroundColor = [UIColor grayColor];
        
        lab = [UILabel new];
        lab.backgroundColor = [UIColor whiteColor];
        lab.frame = CGRectMake(20, 100, 280, 30);
        [self.view addSubview:lab];
        lab.text = @"准备链接。。。";
        
        
        [self initBluetooth];
    }
    
    - (void)initBluetooth{
        _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];//创建CBCentralManager对象
    
    }
    
    - (void)scanBluetooth
    {
        NSLog(@"BluetoothBase scanBluetooth");
        //CBCentralManagerScanOptionAllowDuplicatesKey值为 No,表示不重复扫描已发现的设备
        NSDictionary *optionDic = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
        [_centralManager scanForPeripheralsWithServices:nil options:optionDic];//如果你将第一个参数设置为nil,Central Manager就会开始寻找所有的服务。
    }
    
    - (void)stopScanBluetooth
    {
        [self.centralManager stopScan];
        NSLog(@"BluetoothBase stopScanBluetooth,已经连接外设停止扫描或者手动停止扫描");
    }
    
    - (void)connectPeripheral:(CBPeripheral *)peripheral
    {
        [self.centralManager connectPeripheral:peripheral options:nil];
        self.peripheral = peripheral;
        peripheral.delegate = self;     //连接时设置代理
    }
    
    #pragma CBCentralManagerDelegate
    
    - (void)centralManagerDidUpdateState:(CBCentralManager *)central
    {
        NSLog(@"centralManagerDidUpdateState:%ld",(long)central.state);
        switch (central.state) {
            case CBCentralManagerStateUnknown:
                NSLog(@"CBCentralManagerStateUnknown");
                break;
            case CBCentralManagerStateResetting:
                NSLog(@"CBCentralManagerStateResetting");
                break;
            case CBCentralManagerStateUnsupported:
                NSLog(@"CBCentralManagerStateUnsupported");
                break;
            case CBCentralManagerStateUnauthorized:
                NSLog(@"CBCentralManagerStateUnauthorized");
                break;
            case CBCentralManagerStatePoweredOff:
                NSLog(@"CBCentralManagerStatePoweredOff");
                break;
            case CBCentralManagerStatePoweredOn:
                [self scanBluetooth];   //很重要,当蓝牙处于打开状态,开始扫描。
                break;
            default:
                NSLog(@"蓝牙未工作在正确状态");
                break;
        }
    }
    
    - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI //找到外设的委托
    {
        
        NSLog(@"-------------------------------------");
        NSMutableString* nsmstring=[NSMutableString stringWithString:@"\n"];
        [nsmstring appendString:@"----发现外设----\n"];
        [nsmstring appendString:@"Peripheral Info:\n"];
        [nsmstring appendFormat:@"NAME: %@\n",peripheral.name];
        [nsmstring appendFormat:@"UUID(identifier): %@\n",peripheral.identifier];
        [nsmstring appendFormat:@"RSSI: %@\n",RSSI];
        [nsmstring appendFormat:@"adverisement:%@\n",advertisementData];
        NSLog(@"%@",nsmstring);
        NSLog(@"-------------------------------------");
        
        if ([peripheral.name isEqualToString:@"ky_0002"]) {
           [self connectPeripheral:peripheral];
           [self stopScanBluetooth];
        }
    }
    
    -(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral//连接外设成功的委托
    {
        NSLog(@"%@连接成功",peripheral.name);
        lab.text = [NSString stringWithFormat:@"%@连接成功",peripheral.name];
        
        //查找该周边设备的服务
        [peripheral discoverServices:nil];
    }
    
    - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error//外设连接失败的委托
    {
        NSLog(@"%@连接断开",peripheral.name);
    }
    
    -(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error//断开外设的委托
    {
        NSLog(@"断开外设");
        lab.text = [NSString stringWithFormat:@"%@断开连接",peripheral.name];
    
        //重连
        [self connectPeripheral:peripheral];
        //本地通知
        [self addLocalNotification];
    }
    
    
    
    #pragma CBPeripheralDelegate
    
    // 发现外设的服务后调用的方法
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error{
        NSLog(@"发现外围设备的服务");
        if (error)
        {
            NSLog(@"%s, line = %d, error = %@", __FUNCTION__, __LINE__, error.localizedDescription);
            return;
        }
        for (CBService *service in peripheral.services)
        {
            NSLog(@"%@",service);
            NSLog(@"%@",service.UUID);
            
            // 发现服务后,让设备再发现服务内部的特征们
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
    
    //最终找到特征会自动执行这个回调
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error{
        NSLog(@"发现外围设备的特征");
        
        if (error)
        {
            NSLog(@"%s, line = %d, %@", __FUNCTION__, __LINE__, [error description]);
            return;
        }
        
        for (CBCharacteristic *chara in service.characteristics)
        {
            NSLog(@"%@",chara);
            NSLog(@"%@",chara.UUID);
        }
    }
    
    
    #pragma addLocalNotification
    
    - (void)addLocalNotification {
        // 1.创建一个本地通知
        UILocalNotification *localNote = [[UILocalNotification alloc] init];
        
        // 1.1.设置通知发出的时间
        localNote.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
        
        // 1.2.设置通知内容
        localNote.alertBody = @"这是一个推送:你的名片丢失了";
        
        // 1.3.设置锁屏时,字体下方显示的一个文字
        localNote.alertAction = @"赶紧找一找!!!!!";
        localNote.hasAction = YES;
        
        // 1.5.设置通过到来的声音
        localNote.soundName = @"alarm_device1.wav";
        
        // 1.6.设置应用图标左上角显示的数字
        localNote.applicationIconBadgeNumber = 999;
        
        // 1.7.设置一些额外的信息
        localNote.userInfo = @{@"qq" : @"704711253", @"msg" : @"success"};
        
        // 2.执行通知
        [[UIApplication sharedApplication] scheduleLocalNotification:localNote];
    }
    
    
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    /*
    #pragma mark - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */
    
    @end
    
    

    相关文章

      网友评论

          本文标题:iBeacon-微信摇一摇周边

          本文链接:https://www.haomeiwen.com/subject/mcwvvttx.html