1

In my code, I load a URL (an aspx file) in a UIWebview. It loads and displays fine.

[webView loadRequest:requestObject];

I want to inspect the HTML content being loaded on the iPhone. When I display it in UIWebview using the following code, the UIWebview display format is broken, showing lines and tables in word-wrap format.

NSString *htmlContent = [[NSString alloc] initWithContentsOfURL:inputUrl encoding:NSUTF8StringEncoding  error:&error];

[webView loadHTMLString:htmlContent baseURL:nil];

What could cause the difference, when a file is opened using loadRequest versus loadHTMLString as above?

kzia
  • 559
  • 3
  • 8
  • 17

2 Answers2

1

The call to loadHTMLString does not know what URL to use to resolve any relative URLs that are contained within the HTML. This should be passed in baseURL.

combinatorial
  • 9,132
  • 4
  • 40
  • 58
  • Thanks for the reply. I tried specifying the baseURL, but that did not make any difference. I wonder if the problem has something to do with this being an ASPX file (which is processed by the ASP web server, and it returns HTML to the client). – kzia Sep 27 '12 at 03:24
  • I have also noticed that the break in formatting is very similar to when I did not have the correct "UserAgent" specified for iPhone safari browser. As if, the web server is not processing the htmlContent for the correct web browser. – kzia Sep 27 '12 at 03:35
  • 1
    You could try setting a useragent using NSMutableURLRequest, there is an example here... http://stackoverflow.com/questions/1532206/changing-the-useragent-of-nsurlconnection – combinatorial Sep 27 '12 at 04:38
  • Thank you combinatorial. Setting the User-Agent first in the request, and then sending the request via NSURLConnection worked. I converted the NSData returned into NSString and displayed it in WebView using loadHTMLString. – kzia Sep 27 '12 at 19:50
0

Here is the code for anyone who may be interested:

    NSString* userAgent = @"Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3"; // user agent for iPhone browser
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:inputUrl]; // ARC enabled
    [request setValue:userAgent forHTTPHeaderField:@"User-Agent"]; //setting user agent
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // ARC enabled
    NSURL *base = [NSURL URLWithString:@"http://mainwebsitehere"];
    [webView loadHTMLString:str baseURL:base];
kzia
  • 559
  • 3
  • 8
  • 17