代码之家  ›  专栏  ›  技术社区  ›  NoSixties

通过JustWorks连接iPhone和iPad

  •  0
  • NoSixties  · 技术社区  · 8 年前

    我目前正在开发一个应用程序,需要将数据从iPhone发送到iPad。我已经找到了设备,并通过使用 CentralManager 和 PeriphiralManager . 不过,现在它给我一个信息,要求每次配对。但当我按下“否”选项时,它仍然会通过使用JustWorks连接(至少看起来是因为当我进入蓝牙设置时,它只会说“iPad”,我看不到除此之外的设备信息,当我断开连接时,它会完全从列表中消失)。

    我想知道怎么才能确保弹出的配对请求根本没有出现。我读过一些关于在外设上禁用加密的文章,但是我不知道当iPad就是外设的时候该怎么做。我现在使用的代码如下所示(这是我第一次使用 corebluetooth 我现在还在胡思乱想,想弄清楚它是如何工作的)。

    import UIKit
    import CoreBluetooth
    import CoreLocation
    
    class ViewController: UIViewController {
        @IBOutlet weak var receiveLabel: UILabel!
        @IBOutlet weak var sendButton: UIButton!
    
        var centralManager: CBCentralManager!
        var peripheralManager: CBPeripheralManager!
        var peripherals: [CBPeripheral] = []
        var keepScanning: Bool = false
    
        private var timerScanInterval: TimeInterval = 5
        static let SERVICE_UUID = CBUUID(string: "4DF91029-B356-463E-9F48-BAB077BF3EF5")
        static let RX_UUID = CBUUID(string: "3B66D024-2336-4F22-A980-8095F4898C42")
        static let RX_PROPERTIES: CBCharacteristicProperties = .write
        static let RX_PERMISSIONS: CBAttributePermissions = .writeable
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
            peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
        }
    
    }
    
    extension ViewController {
    
        @IBAction func sendMessage(_ sender: UIButton) {
            for per in peripherals {
                centralManager.connect(per, options: nil)
            }
    
        }
    
        func updateAdvertisingData() {
            if peripheralManager.isAdvertising {
                peripheralManager.stopAdvertising()
            }
    
            peripheralManager.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [ViewController.SERVICE_UUID], CBAdvertisementDataLocalNameKey: "Test"])
        }
    
        func initService() {
    
            let serialService = CBMutableService(type: ViewController.SERVICE_UUID, primary: true)
            let rx = CBMutableCharacteristic(type: ViewController.RX_UUID, properties: ViewController.RX_PROPERTIES, value: nil, permissions: ViewController.RX_PERMISSIONS)
            serialService.characteristics = [rx]
    
            peripheralManager.add(serialService)
        }
    
    }
    
    extension ViewController: CBCentralManagerDelegate {
    
        func centralManagerDidUpdateState(_ central: CBCentralManager) {
            switch central.state {
            case .poweredOn:
                centralManager.scanForPeripherals(withServices: [ViewController.SERVICE_UUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey: true])
                break
            default: break
            }
        }
    
        func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
            peripheral.discoverServices(nil)
            peripherals.append(peripheral)
        }
    
    }
    
    extension ViewController: CBPeripheralDelegate, CBPeripheralManagerDelegate {
    
        func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
            if peripheral.state == .poweredOn {
                initService()
                updateAdvertisingData()
            }
        }
    
        func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
            for service in peripheral.services! {
                peripheral.discoverCharacteristics(nil, for: service)
            }
        }
    
        func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
            for characteristic in service.characteristics! {
                let characteristic = characteristic as CBCharacteristic
                let message = "TestMessage".data(using: .utf8)
                peripheral.writeValue(message!, for: characteristic, type: CBCharacteristicWriteType.withResponse)
            }
        }
    
        func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
            for request in requests {
                if let value = request.value {
                    let messageText = String(data: value, encoding: String.Encoding.utf8)
                    receiveLabel.text = messageText
                }
                self.peripheralManager.respond(to: request, withResult: .success)
            }
        }
    
        func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
            peripheral.delegate = self
            peripheral.discoverServices(nil)
        }
    
    }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Paulw11    8 年前

    即使您只搜索宣传您的特定服务的外围设备,当您发现一个外围设备时,您仍会调用

     peripheral.discoverServices(nil)
    

    这将发现所发现的外设(这是另一个iOS设备)上的所有服务,而不仅仅是您的特定服务。

    然后,对于您发现的每一项服务的所有特征,对于您发现的每一项特征,您都可以使用

     let message = "TestMessage".data(using: .utf8)
     peripheral.writeValue(message!, for: characteristic, type: CBCharacteristicWriteType.withResponse)
    

    由于您已发现设备上所有服务的所有特征,然后尝试写入每个特征,如果其中任何特征需要加密,您将触发配对对话框。当您取消配对对话框时,特定的写入将失败,但您的应用程序将继续工作(这就是为什么您在“设置”中看到连接)。

    您应该改进您的代码,以便它只发现您感兴趣的特定服务,并且只尝试根据您的特性编写。这将防止触发配对对话框,因为您的特征不需要加密。