7

Swift アプリ内に、Bluetooth デバイスを見つけて接続するビューがあります。Bluetooth デバイスの電源が入っています。デバイスをスキャンして見つけることができた後、関数を呼び出してデバイスに接続しましたが、フィードバックがありません。接続できない理由がわかりません。

didFailToConnectPeripheral も didConnectPeripheral も値を返しません。

これを機能させるにはどうすればよいですか?

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {

    var manager: CBCentralManager!


    override func viewDidLoad() {
        super.viewDidLoad()
        manager = CBCentralManager (delegate: self, queue: nil)
    }


    func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {

        print("Peripheral: \(peripheral)")

        manager.connectPeripheral(peripheral, options:nil)

        manager.stopScan()

    }



    func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
        print("connected!")
    }

    func centralManager(central: CBCentralManager, didDisconnectPeripheral
        peripheral: CBPeripheral, error: NSError?) {
            print("disconnected!")
    }


    func centralManager(central: CBCentralManager,
        didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
            print("failed")
    }


    func centralManagerDidUpdateState(central: CBCentralManager) {
        print("Checking")
        switch(central.state)
        {
        case.Unsupported:
            print("BLE is not supported")
        case.Unauthorized:
            print("BLE is unauthorized")
        case.Unknown:
            print("BLE is Unknown")
        case.Resetting:
            print("BLE is Resetting")
        case.PoweredOff:
            print("BLE service is powered off")
        case.PoweredOn:
            print("BLE service is powered on")
            print("Start Scanning")
            manager.scanForPeripheralsWithServices(nil, options: nil)
        default:
            print("default state")
        }
    }
}
4

1 に答える 1

11

CBPeripheral接続しようとしているオブジェクトを保持する必要があります。そうしないと、デリゲート メソッドdidDiscoverPeripheralが戻ると解放されます。

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {

    var manager: CBCentralManager!
    var connectingPeripheral: CBPeripheral?


    override func viewDidLoad() {
        super.viewDidLoad()
        manager = CBCentralManager (delegate: self, queue: nil)
    }


    func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {

        print("Peripheral: \(peripheral)")

        self.connectingPeripheral=peripheral    

        manager.connectPeripheral(peripheral, options:nil)

        manager.stopScan()
    }

...

}
于 2016-01-27T00:51:40.733 に答える