我在调用字符串方法时面临一个非常奇怪的问题。
我有一个视图控制器,我通过蓝牙访问/发送/接收信息"默认CoreBlueTooth API"
所以最初在页面上加载我的字符串方法和属性,如Characters.count和方法,如替换正在工作。
但是一旦蓝牙扫描程序开始(特别是我读的时候),我的字符串方法就会停止工作,并且相同的行为会转移到所有应用程序。
收到的错误是:
源代码:
let deadlineTime = DispatchTime.now() + .seconds(4)
DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: {
let getMacIdHex = "a7".lowercased();
// String Charactor count works here
print("Item test:",self.testString.characters.count);
self.writeValueChar(data: getMacIdHex) { (callback) in
print(callback);
self.logTextView.text = self.logTextView.text + "\n" + "value A7 Get Device UID";
print("Item test:",self.testString.characters.count);
// but String Charactor count doesnt works here ,its in call back
self.readValueChar { (command, code, xml) in
//
print("Item test:",self.testString.characters.count);
self.logTextView.text = self.logTextView.text + "\n" + "Mac returned " + command + "\n" + code + "\n" + xml
print(command, code, xml);
let macAddress = xml.replacingOccurrences(of: "0000_", with: "")
//self.lblMacId.text = "MAC address : " + macAddress;
self.theMacAddress = macAddress;
completion(true);
//self.tableView.reloadData();
//UtilityHelper.HideLoader();
}
}
})
}
错误:执行被中断,原因:EXC_BAD_ACCESS(代码= 1,地址= 0x345f3030303000a7)。
我90%肯定,错误来自ble read功能:
func readValueChar(completion: @escaping (_ commandNumber: String, _ signalBit: String, _ xmlStr: String) -> Void){
if(writableCharacteristic != nil){
peripheral.readValue(for: writableCharacteristic!);
//print(writableCharacteristic);
let deadlineTime = DispatchTime.now() + .seconds(2)
RunbackgroundThread(delay:2, completion:{
// DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: {
self.peripheral.readValue(for: self.writableCharacteristic!);
//print(self.writableCharacteristic);
let data = self.writableCharacteristic?.value;
var byteArray: [UInt8] = [];
data?.copyBytes(to: &byteArray, count: (data?.count)!);
let commandNumber = String(format:"%2X", (data?[0])!);
let signalBit = String(format:"%2X", (data?[1])!);
var xmlStr:String = ""
if((data?.count)! >= 2){
var test2 = data?[2..<(data?.count)!]
xmlStr = String(bytes: test2!, encoding: String.Encoding.utf8)!
//print(xmlStr)
}
completion(commandNumber, signalBit, xmlStr);
})
}
}
任何人都可以解释这种行为以及如何解决它。
由于