#ios #swift #xcode #bluetooth #unsafe-pointers
#iOS #swift #xcode #bluetooth #небезопасные указатели
Вопрос:
Я знаю, что этот вопрос задавался несколько раз, но я действительно этого не понимаю.
Я хочу извлечь значение из устройства Bluetooth (miband). В Swift 2 это работало так:
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if characteristic.uuid.uuidString == "FF06" {
let value = UnsafePointer<Int>(characteristic.value!.bytes).memory
print("Steps: (value)")
}
}
Но в swift 3 он выдает ошибку:
Cannot invoke initializer for type 'UnsafePointer<Int>' with an argument list of type '(UnsafeRawPointer)'
И я понятия не имею, как перенести это на swift 3.
Ответ №1:
Вы можете использовать withUnsafeBytes
с pointee
:
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if characteristic.uuid.uuidString == "FF06" {
let value = characteristic.value!.withUnsafeBytes { (pointer: UnsafePointer<Int>) -> Int in
return pointer.pointee
}
print("Steps: (value)")
}
}
Если UnsafePointer
указывало на массив Pointee
, то вы могли бы использовать оператор подстрочного индекса, например pointer[0]
, pointer[1]
, и т.д., а не . pointer.pointee
Для получения дополнительной информации см. SE-0107.
Комментарии:
1. Работает отлично. Спасибо.