How to change the character encoding in UIWebView?

China☆狼群 提交于 2019-12-03 09:42:15

You can do this by manually loading the HTML, modifying it, and then loading the modified content into the UIWebView.

  • manually load the HTML from the page that doesn't include the meta tag, into a string (e.g. use NSURLConnection)
  • using string manipulation, insert your appropriate encoding meta tag into the manually loaded HTML
  • set the HTML in your web view to the modified string using loadHTMLString:

Now, this will work fine for a web page that contains no links. If it contains links, then you will find that after they click on a link, the new page will not have your modification in place. Therefore, you will need to manually intercept all of the clicks. Here's how you can do that:

user454322

This is what I do,
first find out if it is text, if it is, I get the data, set the encoding and load it using UIWebView>loadData:MIMEType:textEncodingName:baseURL.
Here is the code:

  1. Get the MIMEType sending a synchronous HEAD request.
    We want to use a HEAD HTTP request which generally is fast enough.
    And we want to make the request synchronously for two reasons, we need the request's result to continue, and we want to avoid concurrent request problems like this.

     
    NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:url];
    [headRequest setHTTPMethod:@"HEAD"];
    NSHTTPURLResponse *headResponse;
    NSError *error = nil;
    [NSURLConnection sendSynchronousRequest:headRequest
                          returningResponse:&headResponse
                                      error:&error];
    if (error != nil) {
        NSLog(@"loadURLWithString %@",[error localizedDescription]);
    }
    NSString *mimeType = [headResponse MIMEType];
    

       


  2. Then if it is text, load it with UIWebView>loadData:MIMEType:textEncodingName:baseURL
    To maintain the application responsive, it is recommended to put the following code into a block and run it inside a GCD queue.

    
    if([mimeType rangeOfString:@"text"
                       options:NSCaseInsensitiveSearch].location == 0) {
    
       [wview loadData:[NSData dataWithContentsOfURL: url] MIMEType:mimeType
            textEncodingName:encoding baseURL:nil];
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!