title: CBPeripheral being disconnected with UnknownError Code=0 after calling writeValue
body: <p>I'm developing an app that uses Bluetooth to communicate with Smart Devices.
  It needs to authorise iPhone with such scheme:</p>
  
  <ol>
  <li>Scanning devices with some filters of services UUIDs</li>
  <li>Connecting to a device, discovering services, discovering characteristics</li>
  <li>Calling read operation to retrieve public keys</li>
  <li>Exchange received public keys (using ECDH)</li>
  <li>Generate token</li>
  <li>Write encrypted token (using AES) to device using writeValue</li>
  </ol>
  
  <p>That's all, after that I have stable connection and able to interact with my Smart Device (writing values to protected properties).</p>
  
  <p>The question is that when I restart my app and do all of the steps above, except Step_5 (because I have my token generated and validated previous time), on Step_6 delegate method <code>didWriteValueFor:</code> doesn't even get called, instead of this delegate method <code>didDisconnectPeripheral</code> being called with <code>Error Domain=CBErrorDomain Code=0 "Unknown error." UserInfo={NSLocalizedDescription=Unknown error.}</code> and I can't write values to protected characteristics.</p>
  
  <p>I can't get what I'm doing wrong. Any help would be nice.</p>
  
  <p><strong>UPD[0]</strong>: Sometimes I can get a callback for <code>didWriteValueFor:</code> on Step_6 but IMMEDIATELY (like less than a 0.5 sec) iPhone is being disconnected with an error from above.</p>
  
  <p><strong>UPD[1]</strong>: Also I was trying to <code>cancelPeripheralConnection()</code> before closing my app because Smart Device does not handle multiple connections in hardware reasons, but no luck here.</p>
  
  <p><strong>UPD[2]</strong>: Well, after three days of searching for information, I realized that I was digging in the wrong direction at all. The problem was that I interrupted the application with the “Stop” button in Xcode, and didn’t close it manually via iPhone, therefore, <code>willTerminate</code> was not called, and even if it was called, it had a very limited amount of time to execute all the processes that were supposed to be executed, as a result, the connection didn’t interrupt (the <code>cancelPeripheralConnection</code> method was not called), and the next time I started the App, I tried to establish a connection with a device that already has a connection to my App.</p>
  
  <p>At least it started connecting often, but I'm still getting this error sometimes. The main question is: how properly disconnect from the device? For now I’m unsubscribing from all the properties that have <code>isNotify: true</code> (setting to <code>false</code>) and call <code>cancelPeripheralConnection</code>. Do I need to wait the “unsubscribe” process before disconnecting?</p>
  
  <p><strong>UPD[3]</strong>: It doesn't matter if I wait for unsubscribe finished or not. At least it have no effect.</p>