how to add pinch and zoom on a uiwebview - iphone - iphone

I know this question has been asked a couple of times before. I m trying to zoom in / out the uiwebview. How exactly do i do this? I tried setting 'webView.scalesPageToFit=YES;' but its not working.
I also tried this How do I enable the zoom in/out option in a UIWebView? but yet im not able to achieve the zoom in / out
Code
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[actorUrlArray objectAtIndex:_rowNumberInActivity]]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
webView.scalesPageToFit=YES;
what am i missing out here?
NOTE : I'm loading the iphone app on the ipad to check the app. Can that be a problem??
If its the meta tag problem. how do i set them? i tried this code.. but its not working.. i know nothing about javascript.. so im not sure whether this is correct or not..
NSString* js =
#"var meta = document.createElement('meta'); \" \"meta.setAttribute( 'name', 'viewport' ); \" \"meta.setAttribute( 'content', 'width = device-width, initial-scale = 5.0, user-scalable = yes' ); \" \"document.getElementsByTagName('head')[0].appendChild(meta)";
[webView stringByEvaluatingJavaScriptFromString: js];

Zooming in and out and Pinch are built in feature of UIWebView. You don't need to write any code to achieve that.

just simply set the property.
scalesPageToFit=YES
for any pinching and zooming to work on a UIWebView

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]

Which way is faster to load page in uiwebview

Which way is faster to load webpages in uiwebivew
using
Loading NSData into a UIWebView
OR
using Load Request URL?
Network requests take time. There's no point in trying to optimize a few milliseconds off this type of code. Write the code that is most readable / maintainable and it will serve you better.
You could put the webpage, scripts, css, and images in your app bundle; get a URL that points to it (file://...) and use that. Within your webpage, you can use AJAX to pull in some dynamic data, etc.
That'd be a better path to optimize; but it all depends on your situation.
If you have the option of using loadRequest, I'd recommend it. Let the OS take the work off your hands.
edit:
PS: UIWebView tends to take it's time about displaying data; even when no network is involved.
I often set the webview's alpha to 0 in IB or viewDidLoad; then fade it in when the content is ready.
Inside your webViewDidFinishLoad: method, add this:
if (0.0f == webview.alpha) {
[UIView animateWithDuration:0.4f
animations:^{
webview.alpha = 1.0f;
}];
}
Their is really isn't any "technical" way to load Webview faster, But I would recommend you use:
Load Request URL
Load Request URL Code:
#interface WebViewController : UIViewController {
IBOutlet UIWebView *webView;
}
#property (nonatomic, retain) UIWebView *webView;
#end
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewDidLoad {
NSString *urlAddress = #"http://www.google.com";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Request Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}

problems showing the actual URL of a page in my app

I'm making an iPad browser, and I have a little problem. When I go to google, for example, I write the google direction in a textField. The problem is that when I change the web page, it still says http://www.google.com/. Here's my code:
-(IBAction)buttonpressed2:(id)sender {
url = [NSURL URLWithString:[textField text]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
[webView isEqual:textField.text];
}
How can I make the textField show the page that I'm watching right now, and not the first url typed in the field?
First, make sure when you set up the webView, you assign the UIWebViewDelegate to self
Then, implement the delegate method: webViewDidFinishLoad, as such:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSURLRequest *currentRequest = [webView request];
NSURL *currentURL = [currentRequest URL];
//This will log the current url
NSLog(#"Current URL is %#", currentURL.absoluteString);
//Then to display it in the textField
textfield.text = currentURL.absoluteString;
}
Edit:
A delegate is a special set of methods that wait for an event to happen. When that event happens, the appropiate method is called. The method above is one of the delegate methods for a UIWebView - When a specific event happens with the webView, in this case when the webViewDidFinishLoad, that method is automtically called and we can respond as such. In order to set the delegate, we can proceed one of two ways:
If you created the webView in code, this is with something like this:
UIWebView *webView = [[UIWebView alloc] init...]
then all you need to do is add the following line of code:
webView.delegate = self;
However, you might have also created the webView in the interface builder - If that's the case, click on the webView and the linker tab, and drag the delegate option over to "File's Owner".
and thats it.
Your class should implement the UIWebViewDelegate protocol. Then in the method webView:shouldStartLoadWithRequest:navigationType: you can do this:
[textField setText:[[request URL] absoluteString]];
This way the value in the textField will be updated whenever you navigate to a new url.

How to display address in google map application in iphone

I have loaded google map application in iphone . I am using UIWebView Control in that Control i loaded google maps like following
UIWebView *webView;
NSString *url = [NSString stringWithFormat: #"http://maps.google.com/maps?q=1600+Amphitheatre+Parkway,+Mountain+View,+CA"];
NSURL *aURL = [NSURL URLWithString:url];
webView.backgroundColor = [UIColor whiteColor];
NSURLRequest *aRequest = [NSURLRequest requestWithURL:aURL];
webView.dataDetectorTypes=UIWebViewNavigationTypeBackForward;
webView.scalesPageToFit = YES;
webView.autoresizesSubviews = YES;
webView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
//set the web view and acceleration delagates for the web view to be itself
[webView loadRequest:aRequest];
Its work fine with pin point.But i want to display address in google maps application when they click the pin.The pin (i.e its denoted A).
Can anyone help me ?
Thanks in advance......
One more help What i given in the parameters of " q " should be applied in the search box of google maps.I want to avoid this . Any help would be appreciated ?
use MapKit (MKMapView object) instead of a webview pointed to a google map image and use Google Map API to retrieve coordinates of the address.
You can use AddressAnnotation object to create a pin and the addAnnotation method of MKMapView to add it to your map.
Have fun !

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.