Sunday, May 12, 2013

NSString stringWithContentsOfFile encoding error example ios


stringWithContentsOfFile: encoding: error:

Returns a string created by reading data from the file at a given path interpreted using a given encoding.
+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError**)error
Parameters
path
A path to a file.
enc
The encoding of 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, pass in NULL.
Return Value[ NSString stringWithContentsOfFile encoding error example ]
A string created by reading data from the file named by path using the encoding, enc. If the file can’t be opened or there is an encoding error, returns nil.
[ NSString stringWithContentsOfFile encoding error example ]
// The source text file is named "Example.txt". Written with UTF-8 encoding.
NSString* path = [[NSBundle mainBundle] pathForResource:@"Example"
                                                 ofType:@"txt"];
NSError *error = nil;
NSString* content = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                 error:&error];
if(error) { // If error object was instantiated, handle it.
    NSLog(@"ERROR while loading from file: %@", error);
    // …
}
[ NSString stringWithContentsOfFile encoding error example ]
NSStringEncodeing *encoding;
NSError *error;
NSString *myString = [NSString stringWithContentsOfFile:myFilePath usedEncoding:encoding error:error];
[ NSString stringWithContentsOfFile encoding 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;
}