Keep ViewController Content; Prevent ViewController From Reloading – How? - ios

I created an iOS app in Xcode. There are four ViewControllers in my app. You can navigate through the app by tapping the buttons in the bottom toolbar.
How can I prevent a ViewController from reloading when visiting it again?

So there are a couple of ways to keep track of whether the view has been loaded or not. One way is to create singleton and add several boolean properties to monitor whether the view has been loaded. Another way is to us NSUserDefaults to store a property once it has been loaded the first time. If you go that route then here is what the code would look like in your viewDidLoad method:
if (![[[NSUserDefaults standardUserDefaults] objectForKey:#"homeLoadFlag"] isEqualToString:#"YES"]) {
NSURL *url=[NSURL URLWithString: #"http://google.com"];
NSURLRequest * requestURL=[NSURLRequest requestWithURL:url];
[_homewebview loadRequest:requestURL];
[[NSUserDefaults standardUserDefaults] setObject:#"YES" forKey:#"homeLoadFlag"];}
This place a wrapper around your call to load the webView and will only make the call when it's loaded the first time.

This largely depends on what your view controllers contain so it's hard to answer without seeing your code. That said, rather than 'presenting' the view controllers another option would be to hide/unhide the views (or animating them on and off the screen). You could do this with four view controllers or with four views managed by a single controller.
There are a couple of ways of going about this. Personally I would have one viewController that controls all four views. If you are using a storyboard then I would have the toolbar at the bottom and then you can either 1) add the three webviews and the textview to the storyboard - or 2) you can one of the views and then create the other three views programatically. If you went the later route you could simply place the one web view (we'll call it webView1) on the storyboard and then override the viewDidLayoutSubviews and add the lines
-(void)viewDidLayoutSubviews {
CGRect viewFrame=webView1.frame;
UIWebView *webView2=[[UIWebView alloc] initWithFrame:viewFrame];
webView2.hidden=YES;
UIWebView *webView3=[[UIWebView alloc] initWithFrame:viewFrame];
webView3.hidden=YES;
UITextView *textView=[[UITextView alloc] initWithFrame:viewFrame];
textView.hidden=YES;
}
Then on your toolBar you can have your buttons unhide the view you want to show by changing the view property, for example, if you want to show the second webView you would simply say:
webView2.hidden=NO;

Here's the code of one ViewController.h/ViewController.m file:
//
// HomeViewController.h
// App_Single
//
//
#import <UIKit/UIKit.h>
#interface HomeViewController : UIViewController
#property (nonatomic, strong) IBOutlet UIWebView *homewebview;
#property (nonatomic, strong) IBOutlet UIWebView *website;
#end
//
// HomeViewController.m
// App_Single
//
//
#import "HomeViewController.h"
#import <SystemConfiguration/SystemConfiguration.h>
#import "Reachability.h"
#interface HomeViewController ()
#end
#implementation HomeViewController
- (BOOL)connected
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return !(networkStatus == NotReachable);
}
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url=[NSURL URLWithString: #"http://google.com"]; NSURLRequest * requestURL=[NSURLRequest requestWithURL:url]; [_homewebview loadRequest:requestURL];
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipe:)];
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipe:)];
// Setting the swipe direction.
[swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
// Adding the swipe gesture on WebView
[_homewebview addGestureRecognizer:swipeLeft];
[_homewebview addGestureRecognizer:swipeRight];
if (![self connected])
{
// not connected
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Keine Internetverbindung vorhanden!" message:#"No network connection available!" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil];
[alert show];
} else
{
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSUInteger)supportedInterfaceOrientations {
return (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown | UIInterfaceOrientationMaskLandscape);
}
- (IBAction)goHomepage:(id)sender {
NSURL *url=[NSURL URLWithString: #"http://google.com"];
NSURLRequest *requestURL=[NSURLRequest requestWithURL:url];
[_website loadRequest:requestURL];
}
- (IBAction)openSearch:(id)sender {
NSURL *url=[NSURL URLWithString: #"http://google.com/search"];
NSURLRequest *requestURL=[NSURLRequest requestWithURL:url];
[_website loadRequest:requestURL];
}
- (void)handleSwipe:(UISwipeGestureRecognizer *)swipe {
if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) {
[_homewebview goForward];
}
if (swipe.direction == UISwipeGestureRecognizerDirectionRight) {
[_homewebview goBack];
}
}
#end

Related

How to add UIWebView in Cocoa Touch Library and use it in Application

I'm a newbie in iOS programming, i am trying to make an iOS library that can be useful on my future applications. The app will have a button that will call the library and will load a website(the address link will come from the application).
I tried searching but none of it is working.
WebLibrary.h
#import <Foundation/Foundation.h>
#interface WebLibrary : NSObject
- (void)showUIWebView:(NSURL*)urlToOpen
{
/* UIViewController *myVC = [self.navigationController.viewControllers lastObject];
//This is your last view in the navigationController hierarchy.
UIWebView *newWebView = [[UIWebView alloc] initWithFrame:myVC.view.frame];
[myVC.view addSubview:newWebView];
*/
}
#end
WebLibrary.m
#import "WebLibrary.h"
#implementation WebLibrary
/* -(void) showUIWebView:(NSURL*)urlToOpen
{
//some codes here
}
*/
#end
If you want to load an URL on your webview, you need to call the loadRequest: method to perform it, example:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:_urlPath]];
[request addValue:#"YES" forHTTPHeaderField:#"Mobile-App"];
[_webView loadRequest:request];
You can add the webview to your viewcontroller in viewDidLoad method:
-(void) viewDidLoad{
[super viewDidLoad];
//custom your view
_webView = [[UIWebView alloc] initWithFrame: self.view.frame];
_webView.scalesPageToFit = YES;
[self.view addSubView: _webView];
}
You should read about UIViewController and the methods in it to understand clearly.

UIWebView new window request isn't working

I have a code (objective-c) that should open a new window (viewcontroller) when a link with a certain string in a uiwebview is clicked. But it doesn't work.
Here's the code from the .m file:
-(BOOL)webView2:(UIWebView*)webView2 shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = request.URL;
NSString *urlString = url.absoluteString;
//Check if special link
if ( [ urlString isEqualToString: #"http://google.com/" ] ) {
//Here present the new view controller
ViewController *ViewController8 = [[ViewController alloc] init];
[self presentViewController:ViewController8 animated:YES completion:nil];
return NO;
}
return YES;
}
The new viewcontroller subclass name is: ViewController8 and the UIWebView subclass is: webView2
Here's the code from the .h file:
#import <UIKit/UIKit.h>
#interface ViewController8 : UIViewController
#end
#interface ViewController : UIViewController{
IBOutlet UIScrollView *scrollView;
IBOutlet UIButton *openMenu;
int draw1;
}
- (IBAction)OpenMenu:(id)sender;
#property (retain, nonatomic) IBOutlet UIScrollView *scrollView;
#end
How do I fix it so a new window (viewcontroller) is opened when a link with a certain string in a uiwebview is clicked.
First, are you sure about your method signature for the shouldStartLoadWithRequest delegate method?
Did you really override the default method to have it call:
-(BOOL)webView2:(UIWebView*)webView2 shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
???
Or should you instead be replacing "webview2" with "webView" there?
Even if you did, the naming convention would be very confusing.
The default implementation is for a class named "UIWebView", but the delegate method references "webView".
But in your case, you have a class called "webView2", and you're calling a delegate method that should be named:
-(BOOL)webView2:(webView2 *)webView2 shouldStartLoadWithRequest...
Doesn't look right at all.
Somehow I think the problem is mixed up in there. But maybe I'm wrong. So the second question is, have you set a breakpoint at the beginning of your shouldStartLoadWithRequest method to see if it ever gets called?
When you say it "doesn't work", what does that mean? How far does it get?
If it actually gets to the method, then perhaps the problem is that the URL it contains is formatted differently than the string you're looking for. Perhaps the trailing '/' isn't there or "www." is there.
Edit:
I would try something like this:
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSRange rangeOfGoogle = [request.URL.absoluteString rangeOfString:#"google.com"];
//Check if special link
if (rangeOfGoogle.location != NSNotFound) {
//Here present the new view controller
ViewController8 *viewController = [[ViewController8 alloc] initWithNibName:nil bundle:nil];
[self presentViewController:viewController animated:YES completion:nil];
return NO;
}
return YES;
}
I hope this will work for you
-(BOOL)webView:(UIWebView*)webView2 shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSURL *url = request.URL;
NSString *urlString = url.absoluteString;
//Check if special link
if ( [ urlString isEqualToString: #"http://google.com/" ] ) {
//Here present the new view controller
ViewController *ViewController8 = [[ViewController alloc] init];
[self presentViewController:ViewController8 animated:YES completion:nil];
return NO;
}
}
return YES;
}
it works for me.

UIWebView doesn't appear in DetailViewController when called from a button inside a Popover

I have an iOS project with the following files inside it:
**PopOverContentViewController.h,
PopOverContentViewController.m,
MasterViewController.h,
MasterViewController.m,
DetailViewController.h,
DetailViewController.m.**
I created some buttons in PopOverViewController which have this method as their action:
- (void) buttonPressed
{
NSLog(#"The button was pressed");
UIWebView *myWebView = [[UIWebView alloc]
initWithFrame:self.detailViewController.view.bounds];
NSURL *myUrl = [NSURL URLWithString:#"http://www.lau.edu.lb"];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl];
[myWebView loadRequest:myRequest];
[self.detailViewController.view addSubview:myWebView];
if ([self isInPopover])
{
[self.myPopOver dismissPopoverAnimated:YES];
}
}
The problem is that I am not seeing the webpage opening, the DetailviewController doesn't change.
Keep in mind I have the following lines written in PopOverContentViewController.h:
#class DetailViewController;
#property DetailViewController *detailViewController;
And that I have imported DetailViewController.h to the implementation file of PopOverViewController.
I tried loading a page from information in the masterviewcontroller and it appeared in the detailviewcontroller, but I'm clueless as to why it isn't working from the popover.
Thank you!

UIWebView back button implementation issue in iPad

I have implemented a browser in my application by using UIWebView, by default I'm loading google page in my browser.
When I search something in the google page ,the UIWebViewDelegate's webView:shouldStartLoadWithRequest:navigationType: method is called.
The problem is when I tap on the back button from this search page no delegates are getting called, so I am having a problem disabling my back button.
This problem happens only in an iPad application not in an iPhone application.
This code may help u...
A UIWebView is a UIView that can load a web page while remaining in the user's application.
Navigation to other webpages is allowed through the use of imbedded links in a web page itself. Forward and backward navigation through history can be set up with instance methods goForward and goBack, but the programmer must supply the buttons.
The following example uses a UIWebView, and
1) adds forward and backward buttons. The buttons are enabled and highlighted using UIWebViewDelegate optional methods webViewDidStartLoad: and webViewDidFinishLoad:
2) adds a UIActivityIndicatorView which displays while the web page is loading
In the .h file for the WebViewController :
Declare the UIWebView, Optionally : add buttons to control moving forward and backward through browsing history and IBActions for pressing the buttons, Optionally again : add a UIActivityIndicatorView.
#interface WebViewController : UIViewController <UIWebViewDelegate>
{
UIWebView *webView;
UIButton *back;
UIButton *forward;
UIActivityIndicatorView *activityIndicator;
}
#property(nonatomic,retain)IBOutlet UIWebView *webView;
#property(nonatomic,retain)IBOutlet UIButton *back;
#property(nonatomic,retain)IBOutlet UIButton *forward;
#property(nonatomic,retain)IBOutlet UIActivityIndicatorView *activityIndicator;
-(IBAction)backButtonPressed: (id)sender;
-(IBAction)forwardButtonPressed: (id)sender;
#end
//In the .m file for the WebViewController
#implementation WebViewController
#synthesize webView;
#synthesize back;
#synthesize forward;
#synthesize activityIndicator;
//method for going backwards in the webpage history
-(IBAction)backButtonPressed:(id)sender {
[webView goBack];
}
//method for going forward in the webpage history
-(IBAction)forwardButtonPressed:(id)sender
{
[webView goForward];
}
//programmer defined method to load the webpage
-(void)startWebViewLoad
{
//NSString *urlAddress = #"http://www.google.com";
NSString *urlAddress = #"http://cagt.bu.edu/page/IPhone-summer2010-wiki_problemsandsolutions";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}
// acivityIndicator is set up here
- (void)viewDidLoad
{
//start an animator symbol for the webpage loading to follow
UIActivityIndicatorView *progressWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//makes activity indicator disappear when it is stopped
progressWheel.hidesWhenStopped = YES;
//used to locate position of activity indicator
progressWheel.center = CGPointMake(160, 160);
self.activityIndicator = progressWheel;
[self.view addSubview: self.activityIndicator];
[self.activityIndicator startAnimating];
[progressWheel release];
[super viewDidLoad];
//call another method to do the webpage loading
[self performSelector:#selector(startWebViewLoad) withObject:nil afterDelay:0];
}
- (void)dealloc
{
[webView release];
[back release];
[forward release];
[activityIndicator release];
[super dealloc];
}
#pragma mark UIWebViewDelegate methods
//only used here to enable or disable the back and forward buttons
- (void)webViewDidStartLoad:(UIWebView *)thisWebView
{
back.enabled = NO;
forward.enabled = NO;
}
- (void)webViewDidFinishLoad:(UIWebView *)thisWebView
{
//stop the activity indicator when done loading
[self.activityIndicator stopAnimating];
//canGoBack and canGoForward are properties which indicate if there is
//any forward or backward history
if(thisWebView.canGoBack == YES)
{
back.enabled = YES;
back.highlighted = YES;
}
if(thisWebView.canGoForward == YES)
{
forward.enabled = YES;
forward.highlighted = YES;
}
}
#end
/*****************************/
//In viewDidLoad for the class which adds the WebViewController:
WebViewController *ourWebVC = [[WebViewController alloc] initWithNibName:#"WebViewController" bundle:nil];
ourWebVC.title = #"WebView";
[self.view addSubview:ourWebVC];
//release ourWebVC somewhere else
In your case ,You have to ignore/avoid "caching data". Following lines of code may help.
NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.google.com"] cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0];
[webView loadRequest:requestObj];

How to open webView (in Main project) by clicking button on alertView (in dependency project (Zxing))

I am a real noob in ios dev. Now i am working on my study project using Zxing.
I make my own project which included dependency third party libraries(Zxing).
Once I scan QRCode which contains with a URL inside, my project will call a class in Zxing library then alert an alertView.
After that, once I click open button on pop-up alertView, it would open that URL by activating Safari.
the code in Zxing looks like this:
//============================================================
- (void)openURL {
[[UIApplication sharedApplication] openURL:self.URL]; //<===== open URL by Safari browser.
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex != [alertView cancelButtonIndex]) {
// perform the action
[self openURL];
}
}
//========================================================
However, my wish is I would like to open that URL in my own webView which constructed by Interface Builder in my "own project" NOT by Safari. Do you have any suggestions? What I have to code in (void)openURL {} ? I got stuck with this issue for 3 days and I now seem to be crazy [p]
Thank you very much for your advance help.
Cheers,
What i did to do this is that I make a new view controller which has webView in it. A property URLstring which get set when the OpenURL method starts. You have to implement delegate methods of webView if you need. The code that I am using is
in WebViewCOntroller.h
#interface WebViewController : UIViewController <UIWebViewDelegate>{
IBOutlet UIWebView *webView;
UIView *activityView;
}
#property (nonatomic, retain) NSString *buyProductLink;
#end
in WebViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
webView.scalesPageToFit = YES;
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.buyProductLink]];
[webView loadRequest:request];
[request release];
}
- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
return YES;
}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
[activityView removeFromSuperview];
}
- (void) webViewDidFinishLoad:(UIWebView *)webView {
[activityView removeFromSuperview];
[activityView release]; activityView = nil;
}
In openURL method use
WebViewController *webViewVC = [[WebViewController alloc] initWithNibName:#"WebViewController" bundle:nil];
webViewVC.buyProductLink = [NSString stringWithFormat:#"%#",result];
[self.navigationController pushViewController:webViewVC animated:YES];

Resources