Saturday, April 27, 2013

NSFileHandle seekToEndOfFile example ios


seekToEndOfFile

Puts the file pointer at the end of the file referenced by the receiver and returns the new file offset.
- (unsigned long long)seekToEndOfFile
Return Value
The file offset with the file pointer at the end of the file. This is therefore equal to the size of the file.
Special Considerations on [NSFileHandle seekToEndOfFile]
Raises an exception if the message is sent to an NSFileHandle object representing a pipe or socket or if the file descriptor is closed.
Example of [NSFileHandle seekToEndOfFile]

NSData *dataToWrite = [s dataUsingEncoding: NSUTF8StringEncoding];
NSFileHandle* outputFile = [NSFileHandle fileHandleForWritingAtPath:Log_FilePath];
[outputFile seekToEndOfFile];
[outputFile writeData:dataToWrite];

NSFileHandle readToEndOfFileInBackgroundAndNotifyForModes example ios


readToEndOfFileInBackgroundAndNotifyForModes:

Reads to the end of file from the file or communications channel in the background and posts a notification when finished.
- (void)readToEndOfFileInBackgroundAndNotifyForModes:(NSArray *)modes
Parameters
modes
The runloop modes in which the read completion notification can be posted.
Discussion of [NSFileHandle readToEndOfFileInBackgroundAndNotifyForModes]
See readToEndOfFileInBackgroundAndNotify for details of this method's operation. The method differs fromreadToEndOfFileInBackgroundAndNotify in that modes specifies the run-loop mode (or modes) in whichNSFileHandleReadToEndOfFileCompletionNotification can be posted.[NSFileHandle readToEndOfFileInBackgroundAndNotifyForModes]
You must call this method from a thread that has an active run loop.
Example of [NSFileHandle readToEndOfFileInBackgroundAndNotifyForModes]

[handle3 seekToFileOffset:0];
[handle3 readToEndOfFileInBackgroundAndNotifyForModes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];

NSFileHandle readToEndOfFileInBackgroundAndNotify example ios


readToEndOfFileInBackgroundAndNotify

Reads to the end of file from the file or communications channel in the background and posts a notification when finished.
- (void)readToEndOfFileInBackgroundAndNotify
Discussion
This method performs an asynchronous readToEndOfFile operation on a file or communications channel and posts anNSFileHandleReadToEndOfFileCompletionNotification. You must call this method from a thread that has an active run loop.[NSFileHandle readToEndOfFileInBackgroundAndNotify]
The notification includes a userInfo dictionary that contains the data read; access this object using the NSFileHandleNotificationDataItem key.[NSFileHandle readToEndOfFileInBackgroundAndNotify]
Any object interested in receiving this data asynchronously must add itself as an observer of NSFileHandleReadToEndOfFileCompletionNotification. In communication via stream-type sockets, the receiver is often the object returned in the userInfo dictionary of NSFileHandleConnectionAcceptedNotification.
Example of [NSFileHandle readToEndOfFileInBackgroundAndNotify]

- (void)awakeFromNib
{
    NSFileHandle *remoteConnection = [NSFileHandle
fileHandleForReadingAtPath:@"/Users/user/Desktop/file.plist"];

    [[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(readAllTheData:)
name:NSFileHandleReadToEndOfFileCompletionNotification
object:remoteConnection];
    [remoteConnection readToEndOfFileInBackgroundAndNotify];

}

- (void)readAllTheData:(NSNotification *)note {
    NSString *errors = nil;
    NSData *contentsOfDockFile = [note object];
    NSLog(@"%@", contentsOfDockFile);
    NSDictionary *testing = [NSPropertyListSerialization
propertyListFromData:contentsOfDockFile
mutabilityOption:NSPropertyListImmutable format:nil
errorDescription:&errors];
    NSLog(@"%@", testing);

    [[NSNotificationCenter defaultCenter] removeObserver:self
name:NSFileHandleReadToEndOfFileCompletionNotification object:[note
object]];

    [testing release];
}

NSFileHandle readInBackgroundAndNotifyForModes example ios


readInBackgroundAndNotifyForModes:

Reads from the file or communications channel in the background and posts a notification when finished.
- (void)readInBackgroundAndNotifyForModes:(NSArray *)modes
Parameters
modes
The runloop modes in which the read completion notification can be posted.
Discussion of [NSFileHandle readInBackgroundAndNotifyForModes]
See readInBackgroundAndNotify for details of how this method operates. This method differs fromreadInBackgroundAndNotify in that modes specifies the run-loop mode (or modes) in which NSFileHandleReadCompletionNotification can be posted.
You must call this method from a thread that has an active run loop.
Example of [NSFileHandle readInBackgroundAndNotifyForModes]

[handle3 seekToFileOffset:0];
[handle3 readInBackgroundAndNotifyForModes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];

NSFileHandle readInBackgroundAndNotify example ios


readInBackgroundAndNotify

Reads from the file or communications channel in the background and posts a notification when finished.
- (void)readInBackgroundAndNotify
Discussion
This method performs an asynchronous availableData operation on a file or communications channel and posts anNSFileHandleReadCompletionNotification notification on the current thread when that operation is complete. You must call this method from a thread that has an active run loop.[NSFileHandle readInBackgroundAndNotify]
The length of the data is limited to the buffer size of the underlying operating system. The notification includes auserInfo dictionary that contains the data read; access this object using the NSFileHandleNotificationDataItem key.[NSFileHandle readInBackgroundAndNotify]
Any object interested in receiving this data asynchronously must add itself as an observer ofNSFileHandleReadCompletionNotification. In communication via stream-type sockets, the receiver is often the object returned in the userInfo dictionary of NSFileHandleConnectionAcceptedNotification.
Note that this method does not cause a continuous stream of notifications to be sent. If you wish to keep getting notified, you’ll also need to call readInBackgroundAndNotify in your observer method.
Example of [NSFileHandle readInBackgroundAndNotify]
-(void)createSocket 
{
    // create socket and wait for events to come in
    NSSocketPort* serverSock = [[NSSocketPort alloc] initWithTCPPort: 1234];
    socketHandle = [[NSFileHandle alloc] initWithFileDescriptor: [serverSock socket]
                                                 closeOnDealloc: NO];

    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(newConnection:) 
                                                 name: NSFileHandleConnectionAcceptedNotification
                                               object: socketHandle];

    [socketHandle acceptConnectionInBackgroundAndNotify];
}

- (void)newConnection:(NSNotification*)notification
{
    NSLog(@"connection accepted");

    NSDictionary* userInfo = [notification userInfo];
    NSFileHandle* remoteFileHandle = [userInfo objectForKey:
                                      NSFileHandleNotificationFileHandleItem];

    if([[userInfo allKeys] containsObject:@"NSFileHandleError"]){
        NSNumber* errorNo = [userInfo objectForKey:@"NSFileHandleError"];
        if( errorNo ) {
            NSLog(@"NSFileHandle Error: %@", errorNo);
            return;
        }
    }

    [socketHandle acceptConnectionInBackgroundAndNotify];


    [[NSNotificationCenter defaultCenter] addObserver:self 
       selector: @selector(processSocketData:)
           name: NSFileHandleReadCompletionNotification
         object: remoteFileHandle];

    // Send a message to the client, acknowledging that the connection was accepted
    [remoteFileHandle writeData: [@"OK" dataUsingEncoding: NSASCIIStringEncoding]];

    [remoteFileHandle readInBackgroundAndNotify];
}

NSFileHandle readDataToEndOfFile example ios


readDataToEndOfFile

Synchronously reads the available data up to the end of file or maximum number of bytes.
- (NSData *)readDataToEndOfFile
Return Value of [NSFileHandle readDataToEndOfFile]
The data available through the receiver up to maximum size that can be represented by an NSData object or, if a communications channel, until an end-of-file indicator is returned.
Discussion of [NSFileHandle readDataToEndOfFile]
This method invokes readDataOfLength: as part of its implementation.
Example of [NSFileHandle readDataToEndOfFile]
-(NSString *) readToEnd
{
    if (currentOffset >= totalFileLength) { return nil; }

    [fileHandle seekToFileOffset:currentOffset];
    NSData *data = [fileHandle readDataToEndOfFile];
    currentOffset = totalFileLength;
    [fileHandle seekToEndOfFile];

    return [[[NSString alloc] initWithData:data encoding:encoding] autorelease];
}

NSFileHandle readDataOfLength example ios


readDataOfLength:

Synchronously reads data up to the specified number of bytes.
- (NSData *)readDataOfLength:(NSUInteger)length
Parameters
length
The number of bytes to read from the receiver.
Return Value of [NSFileHandle readDataOfLength]
The data available through the receiver up to a maximum of length bytes, or the maximum size that can be represented by an NSData object, whichever is the smaller.
Discussion of [NSFileHandle readDataOfLength]
If the receiver is a file, this method returns the data obtained by reading length bytes starting at the current file pointer. If length bytes are not available, this method returns the data from the current file pointer to the end of the file. If the receiver is a communications channel, the method reads up to length bytes from the channel. Returns an empty NSDataobject if the file is positioned at the end of the file or if an end-of-file indicator is returned on a communications channel. This method raises NSFileHandleOperationException if attempts to determine the file-handle type fail or if attempts to read from the file or channel fail.
Example of [NSFileHandle readDataOfLength]
NSString *testFile = @"/test.txt";
NSFileHandle * file = [NSFileHandle fileHandleForWritingAtPath:testFile];
[file seekToEndOfFile];
[file seekToFileOffset:30];
NSLog(@"offset : %llu", [file offsetInFile]);
[file closeFile];  

Read from file
NSString *testFile = @"/test.txt";
NSFileHandle * file = [NSFileHandle fileHandleForWritingAtPath:testFile];
[file seekToFileOffset:30];
NSLog(@"offset : %llu", [file offsetInFile]);

NSData *databuffer = [file readDataOfLength:10];

[file closeFile];  

 Write to file.
NSString *testFile = @"/test.txt";
NSFileHandle * file = [NSFileHandle fileHandleForWritingAtPath:testFile];
[file seekToFileOffset:30];
NSLog(@"offset : %llu", [file offsetInFile]);

NSData *databuffer = [file readDataOfLength:10];
[file seekToFileOffset:50];
[file writeData:databuffer];

[file closeFile];