Background Loading a url in a uiwebview - iphone

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

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

How to return from webview to rootview in iOS?

I am new to iOS and Objective C programming world. I am trying to create a App which will scan the barcode then use that data to go to a website.
Now, the only issue is when I load the website using a webview, I don't know how to return to mainview/rootview. As, I have made this a view based App, I don't know how to implement navigation controller or simply a back button would do.
I have used this SDK: http://zbar.sourceforge.net/iphone/sdkdoc/
The code:
- (void) imagePickerController: (UIImagePickerController*) reader
didFinishPickingMediaWithInfo: (NSDictionary*) info
{
// ADD: get the decode results
id<NSFastEnumeration> results =
[info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results)
// EXAMPLE: just grab the first barcode
break;
// EXAMPLE: do something useful with the barcode data
resultText.text = symbol.data;
CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);
UIWebView *webView= [[UIWebView alloc] initWithFrame:webFrame];
[webView setBackgroundColor:[UIColor whiteColor]];
NSString *urlAddress= #"http://www.flipkart.com/search/a/books?query=";
urlAddress =[urlAddress stringByAppendingString:resultText.text];
NSURL *url= [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj= [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self.view addSubview:webView];
// [webView release];
/*
// ADD: dismiss the controller (NB dismiss from the *reader*!)
[reader dismissModalViewControllerAnimated: YES];
}
How can I add a back button in the webview so that I can return to main view?
Here you have tutorial how to implement toolbar with UIWebView:
http://iosdeveloperzone.com/2011/05/21/tutorial-building-a-web-browser-with-uiwebview-part-1/
You don't have to implement the navigationBar.
You have create a UIViewController that contains your UIWebView, then you have to put this controller into your current UINavigationCotroller's stack by calling [self.navigationController pushViewController:yourVC animated:YES];, then as #mientus said, call [self.navigationController popToRootViewControllerAnimated:YES]; to back to the root view controller.
So in this case i suggest you to start a new Master-Detail Application project.
If you don't want to do this, in your case just set a tag to your webView and add a UIButton with an action like this:
-(IBAction)removeWebView:(id)sender{
[[self.view viewWithTag:yourWebViewTAG] removeFromSuperView];
}

How to set scroll position on uiwebview

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

How to delete the cache from UIWebview or dealloc UIWebview

Every time I load a new page with UIWebView the before loaded page is shown for a short time.
How can I clear that cache? Another possibility would be to dealloc UIWebview. I tried that but than my UIWebView is always "empty". How should the alloc and dealloc be done in this case?
I noticed that the UIWebView is consuming about 10 MB RAM. Now the UIWebView is loaded together with the ViewController. And the view is autoreleased as well as the UIWebView is autoreleased. Wouldn't it be better to dealloc the WebView each time?
Solution:
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
CGRect frame = CGRectMake(0, 0, 320, 480);
self.webView = [[[UIWebView alloc]initWithFrame:frame] autorelease];
self.webView.scalesPageToFit = YES;
[self.view addSubview:self.webView];
}
- (void) viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[self.webView removeFromSuperview];
self.webView = nil;
}
I had nearly the same problem. I wanted the webview cache to be cleared, because everytime i reload a local webpage in an UIWebView, the old one is shown. So I found a solution by simply setting the cachePolicy property of the request. Use a NSMutableURLRequest to set this property. With all that everything works fine with reloading the UIWebView.
NSURL *url = [NSURL fileURLWithPath:MyHTMLFilePath];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[self.webView loadRequest:request];
Hope that helps!
My solution to this problem was to create the UIWebView programmatically on viewWillAppear: and to release it on viewDidDisappear:, like this:
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.webView = [[[UIWebView alloc]initWithFrame:exampleFrame] autorelease];
self.webView.scalesPageToFit = YES;
self.webView.delegate = self;
self.webView.autoresizingMask = webViewBed.autoresizingMask;
[exampleView addSubview:self.webView];
}
- (void) viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[self.webView removeFromSuperview];
self.webView.delegate = nil;
self.webView = nil;
}
If you do this and your UIWebView doesn't get released you should check it's retain count and understand who is retaining it.
If you want to remove all cached responses, you may also want to try something like this:
[[NSURLCache sharedURLCache] removeAllCachedResponses];
If I had to make a guess your property for webView is
#property (nonatomic, retain) IBOutlet UIWebView *webView;
Correct? The important part is the retain.
self.webView = [[UIWebView alloc]initWithFrame:frame];
The above code allocates a UIWebView (meaning retainCount = 1) and then adds it to self.webView, where it is retained again (retainCount = 2).
Change the code to the following, and your webView should be deallocated.
self.webView = [[[UIWebView alloc]initWithFrame:frame] autorelease];
addSubview: can only be called on UIViews.
//[self.navigationController addSubview:self.webView];
should be
[self.navigationController.view addSubview:self.webView];
I did something simpler, I just set the webView's alpha to 0 on loadRequest and 1 on webViewDidFinishLoad.
thewebview.alpha=0.0;
thewebview.backgroundColor=[UIColor whiteColor];
[thewebview loadRequest:[NSURLRequest requestWithURL:url(str)]];
and
- (void)webViewDidFinishLoad:(UIWebView *)webView {
thewebview.alpha=1.0;
}
(Actually I have a fade-in, as rendering f.ex. a PDF can take 1/5 seconds or so.)
You could also load #"about:blank" after the webview disappears, then it will be empty the next time you access it.

Cannot load alternating urls with UIWebview

I have one view holding a list of videos(buttons which can be clicked, each hold a url) which currently bring up a new view which holds the UIWebview, the only problem is I cant pass the url to the webview depending on which button was clicked.
At the moment I just get an empty UIWebview.
How can the url string be passed to the webview so it can load the correct url for each button?
Regards
NSURL *videoURL = [NSURL URLWithString:#"http://..."];
[webView loadRequest:[NSURLRequest requestWithURL:videoURL]];
UPDATE:
In response to comment #3, here's what you can do:
This goes without saying, but keep a reference to the UIWebView instance in Browser
Add an NSString or NSURL #property to Browser
Pass the URL to the Browser instance right after init
In viewDidLoad:, call loadRequest:
So your code might look like this:
- (void)buttonClicked {
Browser *browser = [[Browser alloc] initWithNibName:nil bundle:nil];
browser.URL = [NSURL URLWithString:#"http..."];
[self presentModalViewController:browser animated:YES];
[browser release];
}
and in Browser's viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
[webView loadRequest:[NSURLRequest requestWithURL:URL]];
}