Swift:为什么我的iOS不能扫描其他蓝牙设备

时间:2015-12-08 01:33:47

标签: ios iphone swift ipad bluetooth

现在我正在做一个应用程序项目,需要我的iPhone扫描其他附近的蓝牙设备并列出来。我想知道我的代码有什么问题吗?

代码:

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate {

    var manager: CBCentralManager!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        manager = CBCentralManager (delegate: self, queue: nil)
    }


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

            print("Peripheral: \(peripheral)")
    }

    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")
        }
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }  
}

我正在使用iPhone 5(iOS 9),我确信我的蓝牙已开启。

当我在iPhone中运行应用程序时,控制台仅记录以下输出:

Checking
BLE service is powered on
Start Scanning

但输出中没有显示蓝牙设备的名称。即使我打开我的iPad(iPad Mini 4 iOS 8),列表仍然无法更新。

有时它会扫描我的MacBook Pro蓝牙,输出会显示:

Peripheral: <CBPeripheral: 0x14d70e00, identifier = 54738076-6C97-FD04-18CF-5E1AF6705865, name = vivien’s MacBook Pro, state = disconnected>

那么,为什么会这样呢?有人可以向我解释一下吗?

1 个答案:

答案 0 :(得分:0)

案例1:
您必须使用GKSession扫描并连接其他iOS设备,而不是CoreBluetooth 案例2:
您的蓝牙设备是蓝牙3.0配件。您的iPhone可以在设置 - >蓝牙中发现并显示它 但是此消息未发送到您的应用,因此您的应用无法发现它 请使用蓝牙4.0配件重试。