UIWebview manipulating SVG 'on the fly' - iphone

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];

Related

Slow loading UIWebView from string

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]

UIWebView has a delay when the load image from url

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')"]];
}

xcode UIWebView loader code HTML

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

how do you load an rtf into a UIWebView with a clear background

I want to load an rtf into a web view with a clear background. The general consensus on creating a UIView with a clear background requires adding html code to set the background-color:transparent like this...
myWebView.backgroundColor = [UIColor clearColor];
mytWebView.opaque = NO;
[yWebView loadHTMLString:#"<html><head><style>body{background-color:transparent;}</style> </head><body>your content here!</body></html>" baseURL:nil];
How do I format the HTML string to include the rtf.
Thanks,
John
You can load the html inside of an NSString using the stringWithFormat method. Assuming a string calledrtf` that holds the contents of your RTF, simply use the following line:
[yWebView loadHTMLString:[NSString stringWithFormat:#"<html><head><style>body{background-color:transparent;}</style> </head><body> %# </body></html>", rtf] baseURL:nil];
Note the %# where your RTF goes and the nested stringWithFormat: call.

How to inject JQuery into existing page within a UIWebView?

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.