2011-02-10 25 views

Trả lời

0

Giải pháp này là hơi cũ, trước khi giới thiệu táo lõi bluetooth

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    { 
     // Override point for customization after application launch. 


     Class BluetoothManager = objc_getClass("BluetoothManager") ; 
     id btCont = [BluetoothManager sharedInstance] ; 
     [self performSelector:@selector(status:) withObject:btCont afterDelay:1.0f] ; 

     return YES ; 
    } 


    - (void)status:(id)btCont 
    { 
     BOOL currentState = [btCont enabled] ; 
     //check the value of currentState 

    } 
2

Có một cách trên iOS 5 trở lên sử dụng CoreBluetooth. Lớp bạn có thể sử dụng là CBCentralManager. Nó có thuộc tính 'state' mà bạn có thể kiểm tra xem Bluetooth có đang bật hay không. (Enum CBCentralManagerState có (các) giá trị bạn muốn kiểm tra).

+0

Điều này sẽ chỉ hoạt động đối với các thiết bị có BT LE, tức là iPhone 4S +, iPad 3+ – domsom

41

Một chút nghiên cứu Sam's answer mà tôi nghĩ rằng tôi muốn chia sẻ Bạn có thể làm như vậy mà không sử dụng API tư nhân, nhưng với một vài hãy cẩn thận:

  • Nó sẽ chỉ làm việc trên iOS 5.0+
  • Nó sẽ chỉ hoạt động trên các thiết bị hỗ trợ thông số LE Bluetooth (iPhone 4S +, thế hệ thứ 5 iPod +, iPad Thế hệ thứ ba +)
  • Đơn giản chỉ định phân bổ sẽ khiến ứng dụng của bạn yêu cầu quyền sử dụng ngăn xếp bluetooth từ người dùng (có thể không t được mong muốn) và nếu họ từ chối, điều duy nhất bạn sẽ thấy là CBCentralManagerStateUnauthorized
  • Truy xuất trạng thái bluetooth không đồng bộ và liên tục. Bạn sẽ cần phải thiết lập một đại biểu để có được thay đổi trạng thái, như kiểm tra trạng thái của một người quản lý bluetooth mới được phân bổ sẽ trở lại CBCentralManagerStateUnknown

Điều đó đang được nói, phương pháp này dường như cung cấp cập nhật thời gian thực trạng thái ngăn xếp bluetooth.

Sau bao gồm khuôn khổ CoreBluetooth,

#import <CoreBluetooth/CoreBluetooth.h> 

Các xét nghiệm đều dễ dàng để thực hiện sử dụng:

- (void)detectBluetooth 
{ 
    if(!self.bluetoothManager) 
    { 
     // Put on main queue so we can call UIAlertView from delegate callbacks. 
     self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()]; 
    } 
    [self centralManagerDidUpdateState:self.bluetoothManager]; // Show initial state 
} 

- (void)centralManagerDidUpdateState:(CBCentralManager *)central 
{ 
    NSString *stateString = nil; 
    switch(self.bluetoothManager.state) 
    { 
     case CBCentralManagerStateResetting: stateString = @"The connection with the system service was momentarily lost, update imminent."; break; 
     case CBCentralManagerStateUnsupported: stateString = @"The platform doesn't support Bluetooth Low Energy."; break; 
     case CBCentralManagerStateUnauthorized: stateString = @"The app is not authorized to use Bluetooth Low Energy."; break; 
     case CBCentralManagerStatePoweredOff: stateString = @"Bluetooth is currently powered off."; break; 
     case CBCentralManagerStatePoweredOn: stateString = @"Bluetooth is currently powered on and available to use."; break; 
     default: stateString = @"State unknown, update imminent."; break; 
    } 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Bluetooth state" 
                message:stateString 
                delegate:nil 
              cancelButtonTitle:@"ok" otherButtonTitles: nil]; 
    [alert show]; 
} 
+2

Bạn đã đề cập một cách ngầm định, nhưng để nhất quán: khai báo thuộc tính '@property (nonatomic, strong) CBCentralManager * bluetoothManager;' và đặt lớp của bạn tuân theo giao thức 'CBCentralManagerDelegate' –

+1

Điều này đã không làm việc cho tôi. Có ai đó đã làm việc này cho họ không? iOS7 + – achi

+1

Bạn có thể tránh thông điệp cảnh báo bằng cách sử dụng trình khởi tạo được chỉ định trên CBCentralManager, xem câu trả lời này: http://stackoverflow.com/a/19367494/823483 – bompf

5

Một số cập nhật về câu trả lời BadPirate, với iOS7 bạn có thể đặt người quản lý trung tâm không để hiển thị cảnh báo khi phân bổ đối tượng người quản lý bằng cách cho nó một NSDictionary có khóa "CBCentralManagerOptionShowPowerAlertKey" được đặt thành 0.

self.cbManager = [[CBCentralManager alloc] initWithDelegate:self 
                  queue:nil 
                 options: 
         [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0] 
                forKey:CBCentralManagerOptionShowPowerAlertKey]]; 
9

Câu trả lời này đã được cập nhật từ Mục tiêu gốc-C thành Swift 4.0.

Giả sử bạn đã tạo trình quản lý bluetooth và đã gán cho đại biểu vào lớp ViewController.

import CoreBluetooth 

extension ViewController : CBCentralManagerDelegate { 
    func centralManagerDidUpdateState(_ central: CBCentralManager) { 
     switch central.state { 
     case .poweredOn: 
      print("powered on") 
     case .poweredOff: 
      print("powered off") 
     case .resetting: 
      print("resetting") 
     case .unauthorized: 
      print("unauthorized") 
     case .unsupported: 
      print("unsupported") 
     case .unknown: 
      print("unknown") 
     } 
    } 
} 
21

Để vô hiệu hóa các thông điệp cảnh báo mặc định, bạn chỉ cần đi qua một từ điển tùy chọn khi bạn nhanh chóng CBPeripheralManager:

SWIFT thử nghiệm trên iOS8 +

import CoreBluetooth 

//Define class variable in your VC/AppDelegate 
var bluetoothPeripheralManager: CBPeripheralManager? 

//On viewDidLoad/didFinishLaunchingWithOptions 
let options = [CBCentralManagerOptionShowPowerAlertKey:0] //<-this is the magic bit! 
bluetoothPeripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: options) 

Rõ ràng bạn cũng cần phải thực hiện Phương thức ủy quyền CKManagerDelegate peripherManagerDidUpdateState như được nêu ở trên cũng như:

func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) { 

    var statusMessage = "" 

    switch peripheral.state { 
    case .poweredOn: 
     statusMessage = "Bluetooth Status: Turned On" 

    case .poweredOff: 
     statusMessage = "Bluetooth Status: Turned Off" 

    case .resetting: 
     statusMessage = "Bluetooth Status: Resetting" 

    case .unauthorized: 
     statusMessage = "Bluetooth Status: Not Authorized" 

    case .unsupported: 
     statusMessage = "Bluetooth Status: Not Supported" 

    case .unknown: 
     statusMessage = "Bluetooth Status: Unknown" 
    } 

    print(statusMessage) 

    if peripheral.state == .poweredOff { 
     //TODO: Update this property in an App Manager class 
    } 
} 
+0

cách thêm thuộc tính ** CBPeripheralManager ** trong swift.It nói không thể tìm thấy trình khởi tạo cho loại "CBPeripheralManager" –

+0

@ Aravind.A thêm 'nhập CoreBluetooth' vào đầu tệp nguồn của bạn – Awesomeness

+1

Đoạn mã này rất tuyệt vời cho im lặng kiểm tra tình trạng bluetooth (bật/tắt, vv ..) –