Sunday, May 12, 2013

NSInputStream inputStreamWithURL example ios


inputStreamWithURL:

Creates and returns an initialized NSInputStream object that reads data from the file at a given URL.
+ (id)inputStreamWithURL:(NSURL *)url
Parameters
url
The URL to the file.
Return Value
An initialized NSInputStream object that reads data from the URL at url. If the file specified by url doesn’t exist or is unreadable, returns nil.
( NSInputStream inputStreamWithURL example )
NSInputStream *inputStream = [NSInputStream inputStreamWithURL: myURL];
NSOutputStream *outputStream = [NSOutputStream outputStreamToMemory];
( NSInputStream inputStreamWithURL example )
#import <mach/mach_time.h>

@interface NSURL(CopyWithProgress)<NSObject>
- (void) copyFileURLToURL:(NSURL*)destURL withProgressBlock:(void(^)(double, double, double))block;
@end

@implementation NSURL(CopyWithProgress)

- (void) copyFileURLToURL:(NSURL*)destURL
        withProgressBlock:(void(^)(double, double, double))block
{
    ///
    // NOTE: error handling has been left out in favor of simplicity
    //       real production code should obviously handle errors.
    NSUInteger fileSize = [[NSFileManager defaultManager] attributesOfItemAtPath:self.path error:nil].fileSize;

    NSInputStream  *fileInput  = [NSInputStream inputStreamWithURL:self];
    NSOutputStream *copyOutput = [NSOutputStream outputStreamWithURL:destURL append:NO];

    static size_t bufferSize = 4096;
    uint8_t *buffer = malloc(bufferSize);
    size_t   bytesToWrite;
    size_t   bytesWritten;
    size_t   copySize = 0;
    size_t   counter  = 0;

    [fileInput open];
    [copyOutput open];

    uint64_t time0 = mach_absolute_time();

    while (fileInput.hasBytesAvailable) {
        do {
            bytesToWrite = [fileInput read:buffer maxLength:bufferSize];
            bytesWritten = [copyOutput write:buffer maxLength:bytesToWrite];
            bytesToWrite -= bytesWritten;
            copySize     += bytesWritten;
            if (bytesToWrite > 0)
                memmove(buffer, buffer + bytesWritten, bytesToWrite);
        }
        while (bytesToWrite > 0);

        if (block != nil && ++counter % 10 == 0) {
            double percent  = (double)copySize / fileSize;
            uint64_t time1  = mach_absolute_time();
            double elapsed  = (double)(time1 - time0)/NSEC_PER_SEC;
            double estTimeLeft = ((1 - percent) / percent) * elapsed;
            block(copySize, percent, estTimeLeft);
        }
    }

    if (block != nil)
        block(copySize, 1, 0);
}

@end
( NSInputStream inputStreamWithURL example )
- (void)encryptWithSemaphore:(NSURL *)url {
  dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

  __block int total = 0;
  int blockSize = 32 * 1024;

  NSString *encryptedFile = [[url lastPathComponent] stringByDeletingPathExtension];
  NSURL *docsURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
  self.tempURL = [[docsURL URLByAppendingPathComponent:encryptedFile isDirectory:NO] URLByAppendingPathExtension:@"crypt"];

  NSInputStream *inputStream = [NSInputStream inputStreamWithURL:url];
  __block NSOutputStream *outputStream = [NSOutputStream outputStreamWithURL:self.tempURL append:NO];
  __block NSError *encryptionError = nil;

  [inputStream open];
  [outputStream open];

  RNEncryptor *encryptor = [[RNEncryptor alloc] initWithSettings:kRNCryptorAES256Settings
                                                        password:self.password
                                                         handler:^(RNCryptor *cryptor, NSData *data) {
                                                           @autoreleasepool {
                                                             [outputStream write:data.bytes maxLength:data.length];
                                                             dispatch_semaphore_signal(semaphore);

                                                             data = nil;
                                                             if (cryptor.isFinished) {
                                                               [outputStream close];
                                                               encryptionError = cryptor.error;
                                                               // call my delegate that I'm finished with decrypting
                                                             }
                                                           }
                                                         }];
  while (inputStream.hasBytesAvailable) {
    @autoreleasepool {
      uint8_t buf[blockSize];
      NSUInteger bytesRead = [inputStream read:buf maxLength:blockSize];
      if (bytesRead > 0) {
        NSData *data = [NSData dataWithBytes:buf length:bytesRead];

        total = total + bytesRead;
        [encryptor addData:data];

        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
      }
    }
  }

  [inputStream close];
  [encryptor finish];  
}

NSInputStream inputStreamWithFileAtPath example ios


inputStreamWithFileAtPath:

Creates and returns an initialized NSInputStream object that reads data from the file at a given path.
+ (id)inputStreamWithFileAtPath:(NSString *)path
Parameters
path
The path to the file.
Return Value( NSInputStream inputStreamWithFileAtPath example )
An initialized NSInputStream object that reads data from the file at path. If the file specified by pathdoesn’t exist or is unreadable, returns nil.
( NSInputStream inputStreamWithFileAtPath example )
NSString* fileName = [[NSBundle mainBundle] pathForResource:@"resource" ofType:@".dat"];
NSInputStream* dataStream = [NSInputStream inputStreamWithFileAtPath:fileName];
if (dataStream == nil) {
    NSLog(@"load asset failed");
    return;
}

[dataStream setDelegate:self];
[dataStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                            forMode:NSDefaultRunLoopMode];
[dataStream open];
( NSInputStream inputStreamWithFileAtPath example )
        // Open a stream for the file we're going to send.  We do not open this stream; 
        // NSURLConnection will do it for us.

        self.fileStream = [NSInputStream inputStreamWithFileAtPath:localFilePath];
        assert(self.fileStream != nil);

        [self.fileStream open];

        // Open a CFFTPStream for the URL.

        self.networkStream = CFBridgingRelease(
                                               CFWriteStreamCreateWithFTPURL(NULL, ( CFURLRef) url)
                                               );
        assert(self.networkStream != nil);

        // if ([self.usernameText.text length] != 0) {
        success = [self.networkStream setProperty:@"yourUserName" forKey:(id)kCFStreamPropertyFTPUserName];
        assert(success);
        success = [self.networkStream setProperty:@"yourPassword" forKey:(id)kCFStreamPropertyFTPPassword];
        assert(success);
        //}

        self.networkStream.delegate = self;
        [self.networkStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [self.networkStream open];

        // Tell the UI we're sending.

        [self sendDidStart];
( NSInputStream inputStreamWithFileAtPath example )
// Make sure that this number is larger than the header + 1 block.
// 33+16 bytes = 49 bytes. So it shouldn't be a problem.
int blockSize = 32 * 1024;

NSInputStream *cryptedStream = [NSInputStream inputStreamWithFileAtPath:@"C++ Spec.pdf"];
NSOutputStream *decryptedStream = [NSOutputStream outputStreamToFileAtPath:@"/tmp/C++.crypt" append:NO];

[cryptedStream open];
[decryptedStream open];

// We don't need to keep making new NSData objects. We can just use one repeatedly.
__block NSMutableData *data = [NSMutableData dataWithLength:blockSize];
__block RNEncryptor *decryptor = nil;

dispatch_block_t readStreamBlock = ^{
  [data setLength:blockSize];
  NSInteger bytesRead = [cryptedStream read:[data mutableBytes] maxLength:blockSize];
  if (bytesRead < 0) {
    // Throw an error
  }
  else if (bytesRead == 0) {
    [decryptor finish];
  }
  else {
    [data setLength:bytesRead];
    [decryptor addData:data];
    NSLog(@"Sent %ld bytes to decryptor", (unsigned long)bytesRead);
  }
};

decryptor = [[RNEncryptor alloc] initWithSettings:kRNCryptorAES256Settings
                                         password:@"blah"
                                          handler:^(RNCryptor *cryptor, NSData *data) {
                                            NSLog(@"Decryptor recevied %ld bytes", (unsigned long)data.length);
                                            [decryptedStream write:data.bytes maxLength:data.length];
                                            if (cryptor.isFinished) {
                                              [decryptedStream close];
                                              // call my delegate that I'm finished with decrypting
                                            }
                                            else {
                                              // Might want to put this in a dispatch_async(), but I don't think you need it.
                                              readStreamBlock();
                                            }
                                          }];

// Read the first block to kick things off    
readStreamBlock();