I've a question about load inside the web view:
I create a Json file to get Wordpress table and work well but inside the content table i can get only pure HTML code in one Line, so if i do a request from the web view to load the content like standard code i can't see the content, but only pure code with tags:
[MyWeview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:MyJsonClass.MyContentTeble ]]];
This normal code working, but not to encode HTML, i will get code like:
NSString *HTMLData = #"<iframe></iframe>";
[palinsesto loadHTMLString:HTMLData baseURL:nil];
But my code #"" is get from MyJsonClass.MyContentTable
Thanks for help.
//---------------------------------------------------------------------//
Thx for you answer White, but still not working, if i try to use that code:
[MyWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:MyJsonClass.MyContentTeble ]]];
Working, but i cant see the content.
I try your code and built app good, but crash after touch UITable Cell.
Think i need a Encoder inside the App to read and compile like a NormalWebBrowser a simple HTML code, but never <html><body></body></html> tags T_T because i get pure code and tex from WordPress Table on Mysql DB.
Any other idea?
you might try the following:
[web loadHTMLString: # "<html> <body> <iframe src = 'http://www.example.com', style = 'border-width: 0' width = '100% 'height = '480' frameborder = '0 'scrolling =' no '> </ iframe> </ body> </ html> "baseURL: nil];
- (BOOL) WebView: (UIWebView *) WebView shouldStartLoadWithRequest: (NSURLRequest *) request navigationType: (UIWebViewNavigationType) {navigationType
if ([request.URL.absoluteString rangeOfString: # "www.example.com"]. location! = NSNotFound) {
NSLog (#"%#", [WebView stringByEvaluatingJavaScriptFromString: # "document.body.innerText"]);
return NO;
}
return YES;
}
This is an idea.
I hope you can help
Related
I am trying to load a UIWebView from a string as follows:
NSString* plainContent = #"...";
NSString* htmlContentString = [[NSString stringWithFormat:
#"<html>"
"<style type=\"text/css\">"
"body { background-color:transparent; font-family:Arial-BoldMT; font-size:18;}"
"</style>"
"<body>"
"<p>%#</p>"
"</body></html>", plainContent] retain];
[webView loadHTMLString:htmlContentString baseURL:nil];
Where plain content has some simple HTML with about 5 links and 400 characters. I'm trying to run this on my iPhone5, and the first time it loads it always take a few seconds. Does anyone know why this is happening and how to fix this?
I recently struggled with UIWebView performance. It seemed to take a very long time to process the local HTML I was providing (1 or 2 seconds on iPad Air 2 simulator) even if it was ridiculously small.
After a lot of googling around, I found that the culprit was the phone numbers detection on webview. Once I unchecked it on the storyboard, the latency was gone.
Hope it helps someone facing the same issue :)
This usually happens because of CSS used in rendering web page. It is default behavior when loading page locally. We can also consider that in first load, UIWebview doesn't have cache to this and create cache for that page.
To make it little fast try loading page from a file e.g.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"filePath" ofType:#"html" inDirectory:#"."]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
CSS like body { background-color:transparent; font-family:Arial-BoldMT; font-size:18;} also increase the time of loading a page.
For other who experienced this problems, sometimes we created HTML file by copy-paste-ing from existing websites and we're forget to check the links on header.
In my case, I forgot to remove unused link rel in my html string header:
NSString* html = [NSString stringWithFormat:#"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>%#</title><link type=\"text/css\" rel=\"stylesheet\" href=\"http://192.168.3.183/assets/css/question.css?1383042738\" /></head><body><h1 style=\"font-size: 2em; margin-bottom: 0; color: #3357b8; font-weight: bold\">%#</h1><div style=\"color: #555\">%#</div><br><p style=\"line-height: 1.7em\">%#</p><b>Open in browser</b><br></body></html>", title, title, dateString, content, detail];
The local URL pointed by above link rel make loading time even worst.
<link type=\"text/css\" rel=\"stylesheet\" href=\"http://192.168.3.183/assets/css/question.css?1383042738\" />
Just don't forget to re-check your header or other link in your HTML string and remove it if it is not used.
In case of WKWebView, disabling WKWebView's data detectors worked for me. Swift version:
let webViewCofig = WKWebViewConfiguration()
webViewCofig.dataDetectorTypes = []
webView = WKWebView(frame: view.frame, configuration: webViewCofig)
To enable specific data detector, pass the specific type as .address,.link etc while setting dataDetectorTypes:
config.dataDetectorTypes = [.address]
I have problem with UIWebView delay when the load image from url.
In my code are lines to load local html file:
NSBundle *thisBundle = [NSBundle mainBundle];
NSString *path = [thisBundle pathForResource:#"detail" ofType:#"html"];
NSString *html = [NSString stringWithContentsOfFile:path];
NSString *htmlString = [NSString stringWithFormat:html, imageURL];
[webView loadHTMLString:htmlString baseURL:nil];
and one of lines in my detail.html file:
<img src="%#" height="100%" alt="…"></img>
And now when I push the button and go to UIWebView, at first it is white and after few seconds show image and text.
I know that time is necessary to load image from URL, but is it possible at first show text and next waiting to load image??
Generally I thinking of: push button -> go to UIWebView -> show text -> show image when it's loaded
There are a few things you could do, one would be to just display a view underneath the uiwebview that displays the text.
Set the uiwebview's alpha to be 0 (so its transparent), then when you receive notification that the uiwebview has finished loading use an animation to fade it in, and then remove the view with text.
You will know when the UIWebView has finished loading when the webViewDidFinishLoad: is called.
For the animation something like this:
[UIView animateWithDuration:0.4
animations:^ {
self.webView.alpha = 1.0;
}];
With the help of Martin H, I managed to solve the problem.
First in my local.html file, I was add in <head> section:
<script type="text/javascript">
function loadImage(imageSource) {
document.getElementById("picture").src=imageSource;
}
</script>
next in <body> section:
<img src="" style="border: none;" id="picture">
and next in my UIViewController I was add delegate method:
- (void) webViewDidFinishLoad:(UIWebView *)web {
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"loadImage('http://example.com/image.jpg')"]];
}
I would like to know how to manipulate SVG files that I have loaded into a UIWebview. Currently I am loading an SVG file into an HTML file and then loading that into a UIWebview. I presume that you would use Javascript to do this but am not sure how the go about it exactly. Ideally I would like to be able to manipulate the SVG on the fly in an iPad app. I am aware that you can 'inject' code into the UIWebview but have had no success with my attempts. Clear as mud? Well perhaps a bit of code will help.
Here is how I load the html file into the UIWebview inside the view controller .m file:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString* path = [[NSBundle mainBundle] pathForResource:#"SVG" ofType:#"html"];
NSString* content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
webView = [UIWebView new];
webView.frame = CGRectMake(0, 0, 1024, 768);
webView.dataDetectorTypes = UIDataDetectorTypeAll;
webView.userInteractionEnabled = YES;
[webView loadHTMLString:content baseURL:[[NSBundle mainBundle] bundleURL]];
[self.view addSubview:webView];
[webView release];
}
Here is the code inside the html file that is loaded into the UIWebview:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SVG</title>
</head>
<body>
<object id="circle" data="Circle.svg" width="250" height="250" type="image/svg+xml"/>
</body>
</html>
...and finally here is the code inside the SVG file:
<svg xmlns="http://www.w3.org/2000/svg">
<circle id="redcircle" cx="200" cy="50" r="50" fill="red" />
</svg>
Which creates a nice little red circle in the UIWebview. Now I would like to be able to manipulate the circle on the fly back in the view controller .m file. For example when the user touches the iPad screen, change the fill color attribute to green. Is this even possible?
I hope this all makes sense. It's a bit convoluted. But ultimately what I am trying to do is create graphics on the fly with SVG in an HTML framework and display it in a UIWebview.
Any help would be appreciated. Thanks.
You can execute arbitrary Javascript by passing it to stringByEvaluatingJavaScriptFromString on the webView at any point after the page has first loaded - like in response to a touch event.
So if the Javascript to find the SVG object and change the color looks something like (YMMV, haven't actually tested this):
var path=document.getElementById("circle").getSVGDocument().getElementById("redcircle");path.style.setProperty("fill", "#00FF00", "");
You can execute it with:
NSString *string = #"var path=document.getElementById('circle').getSVGDocument().getElementById('redcircle');path.style.setProperty('fill', '#00FF00', '');";
[webView stringByEvaluatingJavaScriptFromString:string];
Here is the string I want to print:
<p><img src="/Users/Max/Library/Application Support/iPhone Simulator/4.3/Applications/5FCCB847-52D9-48F4-A900-459C6A77A5A6/Documents/18/logo18_lg.jpg" alt="" height="72" /></p>
This is a small fragment of a larger HTML page I have generated in my application, and I am passing to this to the print like so:
UIMarkupTextPrintFormatter *html = [[UIMarkupTextPrintFormatter alloc] initWithMarkupText:printContents];
Where print contents contains all of the html I need to print including the image snippet above. The printing works great EXCEPT for the images not printing.
I'd love to be contradicted, but I don't think you can get the approach you're looking at to work. A work around is to embed the image into the HTML itself. The following illustrates the principle (adapted from this forum post from 2005). You can create a string to represent your image on the fly. A good place to start might be this stackoverflow question.
- (void) buttonTapped;
{
NSString* printContents = #"This is a work around <IMG SRC=\"data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAwAAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUU lvONmOZtfzgFzByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSpa/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQ ZXZeYGejmJlZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwv KOzrcd3iq9uisF81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PHhhx4dbgYKAAA7\">";
UIMarkupTextPrintFormatter *html = [[UIMarkupTextPrintFormatter alloc] initWithMarkupText:printContents];
UIPrintInteractionController* printController = [UIPrintInteractionController sharedPrintController];
[printController setPrintFormatter:html];
[printController presentAnimated:YES completionHandler:^(UIPrintInteractionController *printInteractionController, BOOL completed, NSError *error) {
//
}];
}
It is possible to print HTML with images using UIWebView's viewPrintFormatter instead of configuring UIMarkupTextPrintFormatter with HTML content (which will only print text). You can load your content either from local or remote location and then initiate printing in your webViewDidFinishLoad: method implementation.
Sample Code is available from Apple (found in UIWebView class reference).
SWIFT 3:
It took me a while to figure this out, but if you use the prefix "file://" in front of your URL, then it'll work. Like so:
<p><img src="file:///Users/Max/Library/Application Support/iPhone Simulator/4.3/Applications/5FCCB847-52D9-48F4-A900-459C6A77A5A6/Documents/18/logo18_lg.jpg" alt="" height="72" /></p>
Hope this helps
Suggestion above works perfectly, here is what you need to do it:
download and add this to your project: https://github.com/mikeho/QSUtilities
load your file into NSData:
NSData *logo = [[NSData alloc] initWithContentsOfFile:filePath];
encode using QSStrings to get your encoding, don't forget to change the file type if it is a image/gif:
NSString *encodedJpg = [NSString stringWithFormat:#"data:image/jpg;base64,%#",[QSStrings encodeBase64WithData:logo]];
use the encodedJpg string in the img src like Matthew did above.
this solved a huge problem for me - thank you!
I am trying to inject JQuery into a UIWebView of a page that I can't control, say Google, for example. When a UITextField gets focus, I am executing the following lines of code:
NSString* scriptInject = #"var headElement = document.getElementsByTagName('head')[0]; var script = document.createElement('script');
script.setAttribute('src','http://jquery.com/src/jquery-latest.js');
script.setAttribute('type','text/javascript'); headElement.appendChild(script);";
[myWebView stringByEvaluatingJavaScriptFromString:scriptInject];
[myWebView stringByEvaluatingJavaScriptFromString:#"$(document).ready(function() {$('body').css('background', '#FF0000');}"];
I am executing the background change to validate that I am able to run a JQuery script. I can verify that the Objective-C method is being called, and I even planted an alert for the onload of the newly created <script> tag, so I know that it is being executed in the UIWebView. How do I inject it correctly that I can execute it?
EDIT:
I have event tried this after calling the function to change the color:
[myWebView stringByEvaluatingJavaScriptFromString:#"alert($('body').css());"];
No alert shows.
This has worked for me:
NSString *jqueryCDN = #"http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
NSData *jquery = [NSData dataWithContentsOfURL:[NSURL URLWithString:jqueryCDN]];
NSString *jqueryString = [[NSMutableString alloc] initWithData:jquery encoding:NSUTF8StringEncoding];
[webView stringByEvaluatingJavaScriptFromString:jqueryString];
[webView stringByEvaluatingJavaScriptFromString:/*jquery commands here*/];
Taken from this article.
If jQuery is not in the DOM already you can use stringByEvaluatingJavaScriptFromString: to inject it. I've had similar problem, I wrote a blog post about it: HTML parsing/screen scraping in iOS.