title: Asynchronously decrypt a large file with RNCryptor on iOS
body: <p>I need to asynchronously decrypt a large file with RNCryptor on iOS (so as to show a progress bar). I have found no example anywhere, and thus have tried what I guessed was right, but... what I've come up with doesn't work : the decryptor’s handler is never called, and the thread crashed with EXC_BAD_ADDRESS after sending all data at the end of the function.</p>
  
  <pre><code>NSOutputStream *decryptedStream = [NSOutputStream outputStreamToFileAtPath:decryptedPath append:NO];
  [decryptedStream open];
  
  NSUInteger totalBytesToRead = [[[NSFileManager defaultManager] attributesOfItemAtPath:tempPath error:nil] fileSize];
  __block NSUInteger totalBytesRead = 0;
  
  LOG("I've got %d bytes to decrypt.", totalBytesToRead);
  
  RNDecryptor *decryptor = [[RNDecryptor alloc] initWithPassword:SNCatalogPassword handler:^(RNCryptor *cryptor, NSData *data) {
      totalBytesRead += data.length;
      [decryptedStream write:data.bytes maxLength:data.length];
  
      LOG("Decrypted %d bytes : %d / %d bytes treated", data.length, totalBytesRead, totalBytesToRead);
  
      if (cryptor.isFinished)
      {
          //proceed
          LOG("Done with decrypting.");
  
          [decryptedStream close];
  
      }
  }];
  
  // Feed data to the decryptor
  NSInputStream *cryptedStream = [NSInputStream inputStreamWithFileAtPath:tempPath];
  [cryptedStream open];
  while (cryptedStream.hasBytesAvailable)
  {
      uint8_t buf[4096];
      NSUInteger bytesRead = [cryptedStream read:buf maxLength:4096];
      NSData *data = [NSData dataWithBytes:buf length:bytesRead];
      LOG("Sending %d bytes to decryptor...", bytesRead);
  
      dispatch_async(dispatch_get_main_queue(), ^{
          [decryptor addData:data];
      });
  }
  
  LOG("Sent everything.");
  [decryptor finish];
  [cryptedStream close];
  </code></pre>
  
  <p>(Obvsiouly, <code>tempPath</code> is the path to the crypted file ; <code>decryptedPath</code> is the path where decrypted data should be written).</p>
  
  <p>Also I'm new to ARC so this may be a memory- or dispatch-related problem.</p>
  
  <p>Thanks for any help.</p>