- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我是 Objective-C 和 IOS 开发的新手。我正在尝试使用 BLE 开发应用程序。
我关注DarkBlue
并在 viewDidLoad
添加以下代码在ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.defaultBTServer = [BTServer defaultBTServer];
self.defaultBTServer.delegate = (id)self;
[self.defaultBTServer startScan];
}
而BTServer就像下面的代码:
//
// BTServer.m
// DarkBlue
//
// Created by chenee on 14-3-26.
// Copyright (c) 2014年 chenee. All rights reserved.
//
#import "BTServer.h"
@interface BTServer()
@end
@implementation BTServer{
BOOL inited;
CBCentralManager *myCenter;
//state
NSInteger scanState;
NSInteger connectState;
NSInteger serviceState;
NSInteger characteristicState;
NSInteger readState;
eventBlock connectBlock;
// CBPeripheral *m_Peripheral;
}
static BTServer* _defaultBTServer = nil;
-(NSInteger)getScanState
{
return scanState;
}
-(NSInteger)getConnectState
{
return connectState;
}
-(NSInteger)getServiceState
{
return serviceState;
}
-(NSInteger)getCharacteristicState
{
return characteristicState;
}
-(NSInteger)getReadState
{
return readState;
}
+(BTServer*)defaultBTServer
{
if (nil == _defaultBTServer) {
_defaultBTServer = [[BTServer alloc]init];
[_defaultBTServer initBLE];
}
return _defaultBTServer;
}
-(void)initBLE
{
if (inited) {
return;
}
inited = TRUE;
self.delegate = nil;
self.discoveredPeripherals = [NSMutableArray array];
// self.services = [NSMutableArray array];
self.selectPeripheral = nil;
connectState = KNOT;
connectBlock = nil;
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], CBCentralManagerOptionShowPowerAlertKey, @"zStrapRestoreIdentifier",CBCentralManagerOptionRestoreIdentifierKey,nil];
myCenter = [[CBCentralManager alloc]
initWithDelegate:self
queue:dispatch_queue_create("com.myBLEQueue", NULL)
options:options]; // TODO: options
NSLog(@"init bt server ........");
}
-(void)finishBLE
{
//??
}
#pragma mark -- APIs
-(void)startScan
{
[self startScan:10];
}
-(void)startScan:(NSInteger)forLastTime
{
[self.discoveredPeripherals removeAllObjects];
scanState = KING;
//0:retrive
#if 1
//method 1:
NSArray *atmp = [NSArray arrayWithObjects:[CBUUID UUIDWithString:UUIDPrimaryService],[CBUUID UUIDWithString:UUIDPrimaryService2], nil];
NSArray *retrivedArray = [myCenter retrieveConnectedPeripheralsWithServices:atmp];
NSLog(@"retrivedArray:\n%@",retrivedArray);
for (CBPeripheral* peripheral in retrivedArray) {
[self addPeripheral:peripheral advertisementData:nil RSSI:nil];
}
//method 2:
// [myCenter retrieveConnectedPeripherals];//XXX: deprecated\ˈdɛprɪˌket\ but still work
#endif
//1: scan
// NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
// [myCenter scanForPeripheralsWithServices:[NSArray arrayWithObject:[CBUUID UUIDWithString:@"0xFFA0"]] options:options];
[myCenter scanForPeripheralsWithServices:nil options:nil];
if (forLastTime > 0) {
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(forLastTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// [self stopScan];
// });
// [NSTimer scheduledTimerWithTimeInterval:forLastTime target:self selector:@selector(stopScan) userInfo:nil repeats:NO];
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(stopScan)
object:nil];
[self performSelector:@selector(stopScan)
withObject:nil
afterDelay:forLastTime];
}
}
-(void)stopScan:(BOOL)withOutEvent
{
if (scanState != KING) {
return;
}
NSLog(@"stop scan ...");
scanState = KSUCCESS;
[myCenter stopScan];
if(withOutEvent)
return;
if (self.delegate) {
if([(id)self.delegate respondsToSelector:@selector(didStopScan)]){
[self.delegate didStopScan];
}
}
}
-(void)stopScan
{
[self stopScan:FALSE];
}
-(void)cancelConnect
{
if (myCenter && self.selectPeripheral) {
if(self.selectPeripheral.state == CBPeripheralStateConnecting){
NSLog(@"timeout cancel connect to peripheral:%@",self.selectPeripheral.name);
[myCenter cancelPeripheralConnection:self.selectPeripheral];
connectState = KNOT;
}
}
}
-(void)connect:(PeriperalInfo *)peripheralInfo
{
NSLog(@"connecting to peripheral:%@",peripheralInfo.peripheral.name);
[myCenter connectPeripheral:peripheralInfo.peripheral options:@{CBConnectPeripheralOptionNotifyOnConnectionKey: @YES, CBConnectPeripheralOptionNotifyOnDisconnectionKey: @YES, CBConnectPeripheralOptionNotifyOnNotificationKey: @YES}];
self.selectPeripheral = peripheralInfo.peripheral;
connectState = KING;
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(AUTO_CANCEL_CONNECT_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// [self cancelConnect];
//
// });
// [NSTimer scheduledTimerWithTimeInterval:AUTO_CANCEL_CONNECT_TIMEOUT target:self selector:@selector(cancelConnect) userInfo:nil repeats:NO];
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(cancelConnect)
object:nil];
[self performSelector:@selector(stopScan)
withObject:nil
afterDelay:AUTO_CANCEL_CONNECT_TIMEOUT];
}
-(void)connect:(PeriperalInfo *)peripheralInfo withFinishCB:(eventBlock)callback
{
[self connect:peripheralInfo];
connectBlock = callback;
}
-(void)disConnect
{
if(myCenter && self.selectPeripheral){
[myCenter cancelPeripheralConnection:self.selectPeripheral];
}
}
-(void)discoverService:(CBService*)service
{
if(self.selectPeripheral){
characteristicState = KING;
self.discoveredSevice = service;
[self.selectPeripheral discoverCharacteristics:nil forService:service];
}
}
-(void)readValue:(CBCharacteristic*)characteristic
{
if (readState == KING) {
NSLog(@"BTServer: should wait read over");
return;
}
if (characteristic != nil) {
self.selectCharacteristic = characteristic;
}
readState = KING;
[self.selectPeripheral readValueForCharacteristic:self.selectCharacteristic];
}
#pragma mark CBCentralManagerDelegate
-(void)addPeripheralInfo:(PeriperalInfo *)peripheralInfo
{
for(int i=0;i<self.discoveredPeripherals.count;i++){
PeriperalInfo *pi = self.discoveredPeripherals[i];
if([peripheralInfo.uuid isEqualToString:pi.uuid]){
[self.discoveredPeripherals replaceObjectAtIndex:i withObject:peripheralInfo];
return;
}
}
[self.discoveredPeripherals addObject:peripheralInfo];
if (self.delegate) {
if([(id)self.delegate respondsToSelector:@selector(didFoundPeripheral)]){
[self.delegate didFoundPeripheral];
}
}
}
-(void)addPeripheral:(CBPeripheral*)peripheral advertisementData:(NSDictionary*)advertisementData RSSI:(NSNumber*)RSSI
{
PeriperalInfo *pi = [[PeriperalInfo alloc]init];
pi.peripheral = peripheral;
pi.uuid = [peripheral.identifier UUIDString];
pi.name = peripheral.name;
switch (peripheral.state) {
case CBPeripheralStateDisconnected:
pi.state = @"disConnected";
break;
case CBPeripheralStateConnecting:
pi.state = @"connecting";
break;
case CBPeripheralStateConnected:
pi.state = @"connected";
break;
default:
break;
}
// pi.channel = advertisementData objectForKey:
if (advertisementData) {
pi.localName = [advertisementData objectForKey:CBAdvertisementDataLocalNameKey];
NSArray *array = [advertisementData objectForKey:CBAdvertisementDataServiceUUIDsKey];
pi.serviceUUIDS = [array componentsJoinedByString:@"; "];
}
if (RSSI) {
pi.RSSI = RSSI;
}
[self addPeripheralInfo:pi];
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
// NSLog(@"discover peripheral: %@; advertisementData: %@; RSSI: %@", peripheral, advertisementData, RSSI);
NSLog(@"discover peripheral: %@; RSSI: %@", peripheral.name, RSSI);
[self addPeripheral:peripheral advertisementData:advertisementData RSSI:RSSI];
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(@"didconnect to peripheral: %@",peripheral.name);
connectState = KSUCCESS;
if (connectBlock) {
connectBlock(peripheral,true,nil);
connectBlock = nil;
}
self.selectPeripheral = peripheral;
self.selectPeripheral.delegate = self;
serviceState = KING;
[self.selectPeripheral discoverServices:nil];
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"didDisConnected peripheral: %@",peripheral.name);
connectState = KFAILED;
if (connectBlock) {
connectBlock(peripheral,false,nil);
connectBlock = nil;
}
if (self.delegate) {
if([(id)self.delegate respondsToSelector:@selector(didDisconnect)]){
[self.delegate didDisconnect];
}
}
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"DidFailToConnectPeripheral .....");
}
- (void)centralManager:(CBCentralManager *)central didRetrieveConnectedPeripherals:(NSArray *)peripherals
{
NSLog(@"retrive connected peripheral %@",peripherals);
}
- (void)centralManager:(CBCentralManager *)central didRetrievePeripherals:(NSArray *)peripherals
{
NSLog(@"retrive %@",peripherals);
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
// Determine the state of the peripheral
if ([central state] == CBCentralManagerStatePoweredOff) {
NSLog(@"CoreBluetooth BLE hardware is powered off");
}
else if ([central state] == CBCentralManagerStatePoweredOn) {
NSLog(@"CoreBluetooth BLE hardware is powered on and ready");
}
else if ([central state] == CBCentralManagerStateUnauthorized) {
NSLog(@"CoreBluetooth BLE state is unauthorized");
}
else if ([central state] == CBCentralManagerStateUnknown) {
NSLog(@"CoreBluetooth BLE state is unknown");
}
else if ([central state] == CBCentralManagerStateUnsupported) {
NSLog(@"CoreBluetooth BLE hardware is unsupported on this platform");
}
}
- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary *)dict
{
NSLog(@"will restore ....");
}
#pragma mark CBPeripheralDelegate
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
if (nil == error) {
serviceState = KSUCCESS;
// NSLog(@"found services:\n%@",peripheral.services);
}else{
serviceState = KFAILED;
NSLog(@"discover service failed:%@",error);
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverIncludedServicesForService:(CBService *)service error:(NSError *)error
{
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if (nil == error) {
characteristicState = KSUCCESS;
self.discoveredSevice = service;
}else{
characteristicState = KFAILED;
self.discoveredSevice = nil;
NSLog(@"discover characteristic failed:%@",error);
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error){
readState = KFAILED;
NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, [error localizedDescription]);
return;
}
readState = KSUCCESS;
self.selectCharacteristic = characteristic;
if (self.delegate && [(id)self.delegate respondsToSelector:@selector(didReadvalue)])
[self.delegate didReadvalue];
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error
{
}
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
}
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error
{
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
}
- (void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(NSError *)error
{
}
- (void)peripheralDidUpdateName:(CBPeripheral *)peripheral
{
}
- (void)peripheral:(CBPeripheral *)peripheral didModifyServices:(NSArray *)invalidatedServices
{
}
@end
但是我得到如下错误:
2014-04-10 20:28:24.375 BLE_Running[939:60b] *** Assertion failure in -[CBCentralManager initWithDelegate:queue:options:], /SourceCache/CoreBluetooth/CoreBluetooth-109/CBCentralManager.m:168
2014-04-10 20:28:24.378 BLE_Running[939:60b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'State restoration of CBCentralManager is only allowed for applications that have specified the "bluetooth-central" background mode'
*** First throw call stack:
(0x2fc51f03 0x3a3e6ce7 0x2fc51dd5 0x305fee2f 0x2f971d23 0x8da9d 0x8d7d1 0x89431 0x32485a53 0x32485811 0x3248c489 0x32489dd9 0x324f3a51 0x324f06e5 0x324eacc9 0x32486c97 0x32485df9 0x324ea405 0x34af3b55 0x34af373f 0x2fc1c83f 0x2fc1c7db 0x2fc1afa7 0x2fb857a9 0x2fb8558b 0x324e962b 0x324e4891 0x906b1 0x3a8e4ab7)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
我引用了链接 similar problem , 并添加 Required background modes
像下面的图片
但是好像不行...
这个错误有什么想法吗?
提前致谢。
最佳答案
我点击链接:Core Bluetooth Background Execution Modes
在Info.plist
右键单击并选择Show Raw Keys/Values
在UIBackgroundModes
处,添加item
,它可以看到bluetooth-central
。
关于objective-c - 如何解决 Objective-C 中的 "NSInternalInconsistencyException"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22988363/
我的 iOS 应用程序出现奇怪的错误。从昨天开始一切都运行良好,今天我对一个与 AppDelegate 无关的 View Controller 做了一些改进,当我试图测试我在模拟器上所做的更改时,我得
所以,我正在尝试一下 iOS 编程。时间不多,但我已经推迟学习太久了。但我被这个奇怪的问题困扰了两天。当我尝试将单元格添加到我的 collectionView 时,出现以下错误。 'NSInterna
我的应用程序发生了奇怪的崩溃(仅限 iPad 的 9.x),我不确定如何调试它,因为日志无助于发现正在发生的事情。 最奇怪的是日志显示Auto layout internal error ,但我的应用
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid updat
我想在 swift 中创建一个弹出窗口,并在用户单击按钮时显示它。我不使用 Storyboard , View 是通过编程创建的。 class CreateNoticePopupViewControl
我在仅限 iOS 12 的 crashlytics 上遇到此崩溃。 有人知道这是什么吗?看起来与推送通知相关,但我们的应用中还没有。 致命异常:NSInternalInconsistencyExcep
我已经阅读了有关此错误的所有内容,但仍然无法确定为什么它会在我的应用程序中发生。 使用后台上下文保存多个 Core Data 对象时出现以下错误: *** 由于未捕获的异常“NSInternalInc
我正在尝试从 UITableView 中删除行 -(void) closePickerViewRow:(id) sender { if(self.pickerIsShown && [self.
我在 IOS 上使用 PhoneGap 2.9.0 并为 iPhone5 构建应用程序。 我正在尝试更改启动画面,我遵循了 phonegap 解释 我的行动: 1. 在 iPhone project
对,我有 5 次观看。其中一个 View 称为 RecordViewController。 (RecordViewController 导致错误)我可以很好地切换 View 。但是一旦我进入记录 Vi
在搜索解决方案后我无法解决这个问题,我有这段代码来列出核心数据中的数据: import UIKit import CoreData class ViewControllerClass: UITable
我遇到了一个问题,我有一个忘记密码选项,我在其中放置了一个带有输入字段的 UIAlertView。 UIAlertView *alertView = [[UIAlertView alloc] init
我想用 Objective-C 做一个带有表搜索的 iOS 应用程序。我试过这个项目: https://github.com/versluis/Table-Search-2015 现在我尝试在导航 V
我在 View Controller 之间切换时遇到问题。 我的 md360AppDelegate.h header 如下所示 #import @class md360ViewController;
更新方法: override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingS
每当我尝试使用 AVPlayer 从 url 流式传输歌曲时,我都会收到 NSInternalInconsistencyException 错误。我在结构上制作了一个全局流播放器,以便我的流播放器可以
我正在尝试向我的应用添加容器 View 。但是,它不断崩溃并出现以下错误: 'NSInternalInconsistencyException',原因:'containerView 是必需的。' 我做
尝试保留(更新)标识对象 (persistIdentity:error:) 时版本不匹配失败。对象版本=1229,持久版本=1230。 #10. Crashed: com.twitter.crashl
更新:看来我设法识别了单元格,所以原来的问题解决了。但是现在,截断相同的代码后,出现以下错误: 2012-10-31 15:21:41.857 Laktase[22658:11603] -[NSMan
我有这段代码试图在后台获取 HealthKit 数据。当我第一次运行该应用程序时,代码运行良好,但如果我手动执行后台提取(使用调试命令),我会抛出一个异常并显示一个错误,内容为 reason: 'th
我是一名优秀的程序员,十分优秀!