How to set scroll position on uiwebview - iphone

I want to go to specify line on my uiwebview loaded.
I tried
[webView stringByEvaluatingJavaScriptFromString:#"window.scrollTo(0.0,
100.0)"];
but it's not working. My webview still start with top of the page.
I just wonder its because I load the UIWebview inside UIView.
Check my code below on my UIView:
- (void)loadView {
webview = [[WebViewDetail alloc]initWithFrame:[UIScreen mainScreen].applicationFrame]; //initialize a mainView is a UIWebVIew
webview.managedObjectContext = self.managedObjectContext;
webview.kitab = self.kitab;
webview.currentPasal = self.pasal;
self.title = [NSString stringWithFormat:#"%# %d", self.kitab, webview.currentPasal];
self.view=webview; //make the mainView as the view of this controller
}
and I put the scroll positioning script on my UIWebView:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
int height = [[webView stringByEvaluatingJavaScriptFromString:#"document.body.offsetHeight;"] intValue];
NSString* javascript = [NSString stringWithFormat:#"window.scrollBy(0, %d);", height];
[self stringByEvaluatingJavaScriptFromString:javascript];
}
in this case I want to put my uiwebview go to the bottom of the page when the view is loaded.
But it's totally not working, why?
Am I doing it wrong?

Try
webview.scrollView.contentOffset = CGPointMake(0, 100);

Make sure you set the view controller where you have your web view to be a UIWebViewDelegate, and declare this in the #interface of the header file (.h).
[yourWebView setDelegate:self];
Then, in the webViewDidFinishLoad: method, insert this code:
[yourWebView.scrollView scrollRectToVisible:CGRectMake(0, yourWebView.bounds.size.height + 100, 1, 1) animated:NO];

Related

Press a Button and open a URL in another ViewController

I am trying to learn Xcode by making a simple app.
But I been looking on the net for hours (days) and I cant figure it out how I make a button that open a UIWebView in another ViewController :S
first let me show you some code that I have ready:
I have a few Buttons om my main Storyboard that each are title some country codes like UK, CA and DK.
When I press one of those Buttons I have an IBAction like this:
- (IBAction)ButtonPressed:(UIButton *)sender {
// Google button pressed
NSURL* allURLS;
if([sender.titleLabel.text isEqualToString:#"DK"]) {
// Create URL obj
allURLS = [NSURL URLWithString:#"http://google.dk"];
}else if([sender.titleLabel.text isEqualToString:#"US"])
{
allURLS = [NSURL URLWithString:#"http://google.com"];
}else if([sender.titleLabel.text isEqualToString:#"CA"])
{
allURLS = [NSURL URLWithString:#"http://google.ca"];
}
NSURLRequest* req = [NSURLRequest requestWithURL:allURLS];
[myWebView loadRequest:req];
}
How do I make this open UIWebview on my other Viewcontroller named myWebView?
please help a lost man :D
Well, you've firstViewController already designed and coded, now you've to create secondViewController with a UIWebView binded in IB it self, also it have a setter NSString variable like strUrl that you need to pass at the time of pushing or presenting secondViewController, and assign it to UIWebView in viewDidLoad of secondViewController. See my answer about how to pass a NSString? Also UIWebView has its delegates method (What's delegate & datasource methods? - Apple Doc) Which you can use to handle URL request.
These are the delegate of UIWebView, if you'll going to use it, you need to give UIWebView delegate to self.
- (void)webViewDidStartLoad:(UIWebView *)webView;
- (void)webViewDidFinishLoad:(UIWebView *)webView;
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
firstViewController.m
- (IBAction)ButtonPressed:(UIButton *)sender {
NSURL* allURLS;
//get your URL
secondViewControlelr *secondView=[[secondViewControlelr alloc]init];
second.urlToLoad=allURLS;
[self.navigationController pushViewController:secondView animated:YES];
}
secondViewControlelr.h
//declare url and set property
NSURL *urlToLoad;
secondViewControlelr.m
- (void)viewDidLoad
{
myWebView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
[self.view addSubview:myWebView];
NSURLRequest *urlReq=[NSURLRequest requestWithURL:self.urlToLoad cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:10];
[myWebView loadRequest:urlReq];
}

iOS: Webview causes flicking while navigating to another controller

I use webview in my UIVIewController and load the local HTML file in it using following method.
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:filePath]]];
If I put this method in ViewDidLoad, I can see white flicking while navigating to my controller that doesn't look good.
I tried putting this method in ViewWillAppear like below. I am using webViewLoaded flag to make sure that webview has been loaded then only show the current view else it waits but it is going in infinite loop of waiting!
- (void)viewWillAppear:(BOOL)animated {
webViewLoaded = NO;
webView.scalesPageToFit = allowZoom;
webView.dataDetectorTypes = UIDataDetectorTypeNone;
webView.delegate = self;
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:filePath]]];
int count = 0;
while(webViewLoaded == NO)
{
NSLog(#"Waiting...");
[NSThread sleepForTimeInterval:0.1];
if(count++ > 10) break;
}
}
- (void)webViewDidFinishLoad:(UIWebView *)localwebView {
webViewLoaded = YES;
}
I have also tried the same thing in ViewDidLoad but still its going in infinite loop.
Please note that webViewLoaded is "volatile BOOL" but the webview delegate method is not getting called. Not sure what's going on!
Could anyone please help me to fix this. Thanks.
First : You're blocking your main thread and not giving WebView any chance to finish loading. Never block your main thread.
Second : There are two UIWebView delegate methods : webViewDidFinishLoad and webView:didFailLoadWithError: - make sure to listen to both.
If you're trying to wait until WebView completes loading and only show your controller afterwards - use delegation or blocks. Please note that this is not a proper way of doing things - i'm just modifying your example to make it work :
child controller (with WebView) :
-(void)startLoadingWithParent:(id)_parent {
self.parent = _parent;
NSURL * url = [[NSBundle mainBundle] URLForResource:#"resource" withExtension:#"html"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
[parent showMe:self];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
[parent showError:error];
}
master controller :
-(void)doSomething {
SecondController * ctrl; /// secondController should be created AND has its view loaded at this point
/// ctrl = [SecondController new];
/// ctrl.view;
[ctrl startLoadingWithParent:self];
/// show user that we're doing something - display activity indicator or something
}
-(void)showMe:(UIViewController*)me {
[self.navigationController pushViewControllerAnimated:me];
}
Try using [NSURL fileURLWithPath:filePath]
use Following code for
[self performSelectorInBackground:#selector(webViewLoaded) withObject:nil];
so that it will not affect your UI

Background Loading a url in a uiwebview

Hi I'm a have an app in which i load webpage in a uiwebview .So each time it takes too much time for loading . So i need to load the webpage in a background mode. Any one know how to done this.
Any help would be appreciable.
- (void) start_Web_View {
UIWebView *wv = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,320,460)];
wv.delegate = self;
[wv loadRequest:
[NSURLRequest requestWithURL:
#"http://long_loading_web_site"]];
// go do something else to amuse the user while the web site loads...
}
#pragma mark webview delegate
- (void) webViewDidFinishLoad:(UIWebView *)webView {
[self.view addSubview: webView]; // load is done, so add the webview to self.view so it's visible.
}
Do you want to pre-load that other URL, so when it loads in the main webView it loads faster (or it's already loaded)?
You could create another UIWebView and don't show it at all, and make it load the other URL (you can set the frame of it outside the screen bounds).
Example:
UIWebView *dummyWebView = [[UIWebView alloc] init];
dummyWebView.frame = CGRectMake(-1, -1, 1, 1);

getting HTML source code from webView

I'm making an iphone app...can I get the source from it in objective-c?
Thanks!
Elijah
You can get anything from the web view that JavaScript can return using stringByEvaluatingJavaScriptFromString:. Try something along the lines of
document.lastChild.outerHTML
The document will likely have two child nodes; the first will be the DOCTYPE, and the second the <html> element.
If you need to get the contents of the current URL in your web view you could have something like this in a UIViewController. I didn't compile this code, so there may be some syntax errors, but this should be a solid starting point for your problem.
#interface aViewController : UIViewController <UIWebViewDelegate>
UIWebView *webView;
NSString *htmlSource;
#end
#implementation aViewController
-(void) viewDidLoad {
CGRect webFrame = [[UIScreen mainScreen] applicationFrame];
self.webView = [[UIWebView alloc] initWithFrame:webFrame];
self.webView.delegate = self;
NSURL *aURL = [NSURL URLWithString:#"http://www.myurl.com"];
NSURLRequest *aRequest = [NSURLRequest requestWithURL:aURL];
//load the index.html file into the web view.
[self.webView loadRequest:aRequest];
}
//This is a delegate method that is sent after a web view finishes loading content.
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSLog(#"finished loading");
self.htmlSource = [[NSString alloc] initWithData:[[webView request] HTTPBody] encoding:NSASCIIStringEncoding];
}
#end

UIWebView gets cleared after dismissing a fullscreen modal

I have a UIWebView which loads a html string on viewDidLoad. It detects if the user clicks a link and display a modal view, but when i close the modal view the UIWebView's html has gone! If i use a FormSheet Modal Style the content stays behind, its only fullscreen modals that cause this. Obviously i can just input the html string again on viewWillAppear which fixes it but this causes makes the content flick back on which i don't want. heres my code:
-(void)viewDidLoad {
[self loadArticleText];
...
}
-(void)loadArticleText {
NSString *htmlHead = #"<html><head>...";
NSString *htmlFoot = #"</body></html>";
NSString *htmlContent = [self.articleData valueForKey:#"fulltext"];
NSString *html = [[NSString alloc] initWithFormat:#"%#%#%#", htmlHead, htmlContent, htmlFoot];
[self.articleView loadHTMLString:html baseURL:nil];
[html release];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSURL *URL = [request URL];
ImageViewer *imageView = [[[ImageViewer alloc] initWithNibName:#"ImageViewer" bundle:nil] autorelease];
imageView.imageURL = URL;
[self presentModalViewController:imageView animated:YES];
return NO;
} else {
return YES;
}
}
If i change 'return NO;' to 'return YES;' the webView contents stays, like it should, but obviously it loads the image.
Any help??
Thanks
[self presentModalViewController:ImageView animated:YES];
It looks like you are making a class call rather than an instance call on ImageView.