Saturday, May 18, 2013

NSString initWithContentsOfURL usedEncoding error example ios

[NSString initWithContentsOfURL usedEncoding error]

Returns an NSString object initialized by reading data from a given URL and returns by reference the encoding used to interpret the data.
- (id)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
The URL from which to read data.
Upon return, if url is read successfully, contains the encoding used to interpret the data.
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 of [NSString initWithContentsOfURL usedEncoding error]
An NSString object initialized by reading data from url. If url can’t be opened or the encoding cannot be determined, returns nil. The returned initialized object might be different from the original receiver
[NSString initWithContentsOfURL usedEncoding error] example
NSError *error = nil;
NSStringEncoding encoding = 0;

NSString *tryString = [[NSString alloc] initWithContentsOfURL:url
[NSString initWithContentsOfURL usedEncoding error] example
- (void)viewDidLoad

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"TermsConditions" withExtension:@"html"];

    NSStringEncoding *encoding;
    NSError *error;

    NSString *myHtml = [[NSString alloc] initWithContentsOfURL:modelURL usedEncoding:&encoding error:&error];
    [self.TermsWebView loadHTMLString:myHtml baseURL:modelURL];
    [myHtml release];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
[NSString initWithContentsOfURL usedEncoding error] example
NSError *error = NULL;
NSStringEncoding actualEncoding;

// variable names in Objective-C should usually start with lower case letters, so change
// URL in your code to "url", or even something more descriptive, like "urlOfOurString"
NSString *string = [[NSString alloc] initWithContentsOfURL:urlOfOurString usedEncoding:&actualEncoding error:&error];
    NSLog( @"hey, I actually got a result of %@", string);

    if(actualEncoding != NSUTF8StringEncoding)
        // I also suspect the string you're trying to load really isn't UTF8
        NSLog( @"and look at that, the actual encoding wasn't NSUTF8StringEncoding");
} else {
    NSLog( @"error when trying to fetch from URL %@ - %@", [urlOfOurString absoluteString], [error localizedDescription]);