質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Bluetooth

Bluetoothとは短距離の間でデータを交換するための無線通信規格である。固定・モバイル両方のデバイスから、短波の電波送信を行うことで、高いセキュリティをもつパーソナルエリアネットワーク(PAN)を構築する。

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

0回答

4492閲覧

swift Bluetoothでのテキストの送受信について

youbin

総合スコア6

Bluetooth

Bluetoothとは短距離の間でデータを交換するための無線通信規格である。固定・モバイル両方のデバイスから、短波の電波送信を行うことで、高いセキュリティをもつパーソナルエリアネットワーク(PAN)を構築する。

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2018/02/24 13:28

編集2018/02/25 02:09

Bluetoothのサンプルアプリを「iOS×BLE Core Bluetoothプログラミング」を参考にしながら作っているのですが、接続は出来ているのですが値の送信はできていないみたいでTextViewに値が表示されません。
どのようにすれば表示されるのでしょうか?
Bluetoothについて始めたばかりでよく分かってないです...

swift

1import UIKit 2import CoreBluetooth 3 4class ViewController: UIViewController, UITextViewDelegate, CBCentralManagerDelegate, CBPeripheralDelegate, CBPeripheralManagerDelegate { 5 6 var isScanning = false 7 var centralManager: CBCentralManager! 8 var peripheral: CBPeripheral! 9 var peripheralManager: CBPeripheralManager! 10 var characteristic: CBMutableCharacteristic! 11 12 // アドバタイズしたいサービスのUUIDのリスト 13 let serviceUUID = CBUUID(string: "0000") 14 15 @IBOutlet weak var textView: UITextView! 16 17 override func viewDidLoad() { 18 super.viewDidLoad() 19 20 textView.delegate = self 21 22 self.centralManager = CBCentralManager(delegate: self, queue: nil) 23 self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil) 24 25 } 26 27 override func didReceiveMemoryWarning() { 28 super.didReceiveMemoryWarning() 29 // Dispose of any resources that can be recreated. 30 } 31 32 // セントラル 33 func centralManagerDidUpdateState(_ central: CBCentralManager) { 34 35 print("state (central.state)"); 36 } 37 38// 周辺にあるデバイスを発見すると呼ばれる 39 func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { 40 41 print("発見したBLEデバイス: (peripheral)") 42 self.peripheral = peripheral 43 self.centralManager.connect(self.peripheral, options: nil) 44 } 45 46 // ペリフェラルへの接続が成功すると呼ばれる 47 func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { 48 print("接続成功!") 49 // サービス探索結果を受け取るためにデリゲートをセット 50 peripheral.delegate = self 51 // サービス探索開始 52 peripheral.discoverServices(nil) 53 } 54 55 // ペリフェラルへの接続が失敗すると呼ばれる 56 func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { 57 print("接続失敗・・・") 58 } 59 60 // サービス発見時に呼ばれる 61 func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { 62 63 let services: NSArray = peripheral.services! as NSArray 64 print("(services.count)個のサービスを発見! (services)") 65 66 for obj in services { 67 68 if let service = obj as? CBService { 69 70 // キャラスタリスティック探索開始 71 peripheral.discoverCharacteristics(nil, for: service) 72 73 } 74 } 75 } 76 77 func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { 78 79 let characteristics: NSArray = service.characteristics! as NSArray 80 print("(characteristics.count)個のキャラスタリスティックを発見! (characteristics)") 81 82 for obj in characteristics { 83 84 if let characteristic = obj as? CBCharacteristic { 85 86 // Read専用のキャラスタリスティックに限定して読み出す 87 if characteristic.properties == CBCharacteristicProperties.read { 88 89 peripheral.readValue(for: characteristic) 90 } 91 } 92 } 93 } 94 95 // データ読み出しが完了すると呼ばれる 96 func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { 97 98 if let error = error { 99 print("読み出し失敗...error: (error), characteristic uuid: (characteristic.uuid)") 100 return 101 } 102 103 print("読み出し成功! service uuid: (characteristic.service.uuid), characteristic uuid: (characteristic.uuid), value: (characteristic.value)") 104 105 if characteristic.uuid.isEqual(CBUUID(string: "2A19")) { 106 107 var byte: CUnsignedChar = 0 108 109 if let data = characteristic.value { 110 111 (data as NSData).getBytes(&byte, length: 1) 112 113 } 114 115 print("Battery Level: (byte)") 116 } 117 118 let textdata = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue) 119 print(textdata) 120 textView.text = textdata as! String 121 } 122 123 124 // ペリフェラル 125 126 func publishservice () { 127 // サービスを作成 128 //let serviceUUID = CBUUID(string: "0000") 129 let service = CBMutableService(type: serviceUUID, primary: true) 130 131 // キャラクタリスティックを作成 132 let characteristicUUID = CBUUID(string: "0001") 133 characteristic = CBMutableCharacteristic( 134 type: characteristicUUID, 135 properties: .read, 136 value: nil, 137 permissions: .readable) 138 139 140 // キャラクタリスティックをサービスにセット 141 service.characteristics = [characteristic] 142 143 // サービスを追加 144 peripheralManager.add(service) 145 146 // 値をセット 147 let value = UInt8(arc4random() & 0xFF) 148 let data = NSData(bytes: [value], length: 1) 149 characteristic.value = data as Data; 150 151 let text = "hohohoho" 152 let textdata = text.data(using: String.Encoding.utf8) 153 characteristic.value = textdata 154 } 155 156 func startAdvertise() { 157 158 // アドバタイズメントデータを作成する 159 let advertisementData = [ 160 CBAdvertisementDataLocalNameKey: "Test Device", 161 CBAdvertisementDataServiceUUIDsKey: [serviceUUID] 162 ] as [String : Any] as [String : Any] 163 164 // アドバタイズ開始 165 peripheralManager.startAdvertising(advertisementData) 166 167 //advertiseBtn.setTitle("STOP ADVERTISING", for: UIControlState.normal) 168 } 169 170 func stopAdvertise () { 171 // アドバタイズ停止 172 peripheralManager.stopAdvertising() 173 174 //advertiseBtn.setTitle("START ADVERTISING", for: UIControlState.normal) 175 } 176 177 func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { 178 179 print("state: (peripheral.state)") 180 181 switch peripheral.state { 182 case .poweredOn: 183 // サービス登録開始 184 publishservice() 185 default: 186 break 187 } 188 } 189 190 // サービス追加処理が完了すると呼ばれる 191 func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) { 192 if let error = error { 193 print("サービス追加失敗! error: (error)") 194 return 195 } 196 print("サービス追加成功!") 197 198 // アドバタイズ開始 199 startAdvertise() 200 } 201 202 func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { 203 204 if let error = error { 205 print("アドバタイズ開始失敗! error: (error)") 206 return 207 } 208 print("アドバタイズ開始成功!") 209 210 } 211 212 // Readリクエスト受信時に呼ばれる 213 func peripheralManager(peripheral: CBPeripheralManager, didReceiveReadRequest request: CBATTRequest) { 214 print("Readリクエスト受信! requested service uuid:(request.characteristic.service.uuid) characteristic uuid:(request.characteristic.uuid) value:(request.characteristic.value)") 215 216 // プロパティで保持しているキャラクタリスティックへのReadリクエストかどうかを判定 217 if request.characteristic.uuid.isEqual(characteristic.uuid) 218 { 219 // CBMutableCharacteristicのvalueをCBATTRequestのvalueにセット 220 request.value = characteristic.value 221 222 // リクエストに応答 223 peripheralManager.respond( 224 to: request, 225 withResult: .success) 226 } 227 } 228 229 @IBAction func receptionBtn(_ sender: UIButton) { 230 if !isScanning { 231 isScanning = true 232 centralManager.scanForPeripherals(withServices: nil, options: nil) 233 sender.setTitle("STOP SCAN", for: UIControlState.normal) 234 } else { 235 centralManager.stopScan() 236 sender.setTitle("START SCAN", for: UIControlState.normal) 237 isScanning = false 238 } 239 } 240 241 @IBAction func sendBtn(_ sender: UIButton) { 242 if !peripheralManager.isAdvertising { 243 startAdvertise() 244 } else { 245 stopAdvertise() 246 } 247 }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問