Sunday, May 12, 2013

NSString stringWithContentsOfFile usedEncoding error example ios

stringWithContentsOfFile: usedEncoding: error:
Returns a string created by reading data from the file at a given path and returns by reference the encoding used to interpret the file.
+ (id)stringWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
Parameters
path
A path to a file.
enc
Upon return, if the file is read successfully, contains the encoding used to interpret the file at path.
error
If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
Return Value[ NSString stringWithContentsOfFile usedEncoding error example ]
A string created by reading data from the file named by path. If the file can’t be opened or there is an encoding error, returns nil.
Discussion
This method attempts to determine the encoding of the file at path.

[ NSString stringWithContentsOfFile usedEncoding error example ]
NSStringEncodeing *encoding;
NSError *error;
NSString *myString = [NSString stringWithContentsOfFile:myFilePath usedEncoding:encoding error:error];
[ NSString stringWithContentsOfFile usedEncoding error example ]
- (NSString*) stringFromFile: (NSString*) filePath;
{    
     NSError* error = nil;
     NSString* stringFromFile = [NSString stringWithContentsOfFile: fileName
                                                          encoding: NSUTF8StringEncoding
                                                             error: &error];

     if (stringFromFile) return stringFromFile; // success

     NSLog(@"String is not UTF8 encoded. Error: %@", [error localizedDescription]);

     NSStringEncoding encoding = 0;
     NSError* usedEncodingError = nil;

     NSString* stringFromFile = [NSString stringWithContentsOfFile: path
                                                      usedEncoding: &encoding 
                                                             error: &usedEncodingError];

    if (stringFromFile)
    {
        NSLog(@"Retrieved string using an alternative encoding. Encoding was: %d", encoding);
        return stringFromFile;
    }

   // either handle error or attempt further explicit unencodings here

   return nil;
}