iOS: NSURLRequest returns the same page each time on different storyboards - objective-c

I have a UIWebView class that is added to each storyboard on load, but when passing into this class the page I require form the parent ViewController it only show the file from the first ever page and on each different page/viewController its the same even though I set it different on each.
Is it somehow caching this page and if so, how can I have a clean UIWebview everytime?
my UIwebview class m file (ContentView.m):
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
NSString *urlpath = [[NSBundle mainBundle] pathForResource:pageToDisplay ofType:#"html" inDirectory:#"pageContent"];
NSURL *url=[[NSURL alloc] initFileURLWithPath:urlpath];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[self loadRequest:request];
}
return self;
}
My Parent view passes the requested page using the following variable pageToDisplay:
Parent View m file:
#import "ContentView.h"
- (void)viewDidLoad {
ContentView *dispalyPageContent = [[ContentView alloc] init];
[dispalyPageContent setPageToDisplay:#"THEpg1"];
[self.view addSubview:dispalyPageContent];
//--
[super viewDidLoad];
}
For each other parent view the code is the same but the [displayPageContent setPageToDisplay:#"THEpg1"]; which should change the page I want, e.g. next view would be [displayPageContent setPageToDisplay:#"THEpg2"];
Is it possible to clear this and load a fresh request each time?

It's because when you call ContentView *dispalyPageContent = [[ContentView alloc] init]; in your viewDidLoad , you init it with:
NSString *urlpath = [[NSBundle mainBundle] pathForResource:pageToDisplay ofType:#"html" inDirectory:#"pageContent"];
And in pathForResource:pageToDisplay at the moment of initializing is some trash.
And then, when you call [dispalyPageContent setPageToDisplay:#"smth"] , it changes nothing, because your class ContentView has been already inited with some trash in PageToDisplay
(Also, you call [[ContentView alloc] init]; and in your code there is only initWithFrame:... for objects of ContentView class)
You can solve this in this way:
1) in your ContentView.m
- (id)initWithFrame:(CGRect)frame pageToDisp:(NSString *)pageToDisp {
self = [super initWithFrame:frame];
if (self) {
NSString *urlpath = [[NSBundle mainBundle] pathForResource:pageToDisp ofType:#"html" inDirectory:#"pageContent"];
NSURL *url=[[NSURL alloc] initFileURLWithPath:urlpath];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[self loadRequest:request];
}
return self;
}
2) In your ContentView.h:
- (id)initWithFrame:(CGRect)frame pageToDisp:(NSString *)pageToDisp
3) And then, in viewDidLoad:
- (void)viewDidLoad {
ContentView *dispalyPageContent = [[ContentView alloc] initWithFrame:someFrame pageToDisp:#"THEpg1"];
[self.view addSubview:dispalyPageContent];
//--
[super viewDidLoad];
}

Related

Objective C - When tapping the tab bar item again, how to reload web view again?

I really need help please. Initially, by tapping on a tab bar item, I will load a webview on Gym VC user will then scroll down the web view
What I am trying to accomplish is when user tap on the same tab bar item again, the webView will reload again. I managed to call the method handleRefresh from MyTabBarController But the method doesn't do anything at all. Any guidance is much appreciated.
Currently I have the following code
MyTabBarController.m
#import "GymNavigationController.h"
#import "Gym.h"
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
if([viewController isKindOfClass:[GymNavigationController class]]){
Gym *myGym = [[Gym alloc] init];
[myGym handleRefresh:nil];
}
}
Gym.m
#import "Gym.h"
#import "AppDelegate.h"
#import "GymDet.h"
#import <QuartzCore/QuartzCore.h>
#interface Gym () {
AppDelegate *appDelegate;
NSString *sURL, *sRefresh;
}
#end
#implementation Gym
#synthesize webView;
- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
sURL = appDelegate.gURL;
sURL = [sURL stringByAppendingString:#"/apps/gym.asp?"];
NSLog(#" The sURL to be load for the current page : %# ", sURL);
sRefresh = sURL;
[defaults setObject:sRefresh forKey:#"txtRefresh"];
[defaults synchronize];
NSURL *url = [NSURL URLWithString:sURL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView setDelegate:(id<UIWebViewDelegate>)self];
[webView loadRequest:urlRequest];
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(handleRefresh:) forControlEvents:UIControlEventValueChanged];
[webView.scrollView addSubview:refreshControl];
}
- (void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//[self handleRefresh:nil];
[[self navigationController] setNavigationBarHidden:YES animated:YES];
}
-(void)viewDidDisappear:(BOOL)animated{
[[self navigationController] setNavigationBarHidden:NO animated:YES];
}
- (void)handleRefresh:(UIRefreshControl *)refresh {
//--- Call the stored txtMemCode, something like session ---
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
sRefresh = [defaults objectForKey:#"txtRefresh"];
NSURL *url = [NSURL URLWithString:sRefresh];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
[refresh endRefreshing];
}
First i would like to suggest why you're initiating a new Gym object every time tabbar is tapped you should take a reference of the Gym object and initialise it if its nil then process ahead with the reference, but it maybe your requirement and if it is i would like to suggest you to create a BOOL variable lets say isUpdateRequire and when you're instantiating your viewcontroller assign isUpdateRequire = true. Then in the end of view did load or view will appear (according to your need) check
if isUpdateRequire {
[self handleRefresh:nil]
}
Alternatively you can create protocols in your webviewcontroller and assign its delegate to your tabbarcontroller and fire the delegate method when ever required.
and if you don't want the method to call when you come back to vc simply put this condition in viewWillAppear
if self.isMovingToParentViewController {
[self handleRefresh:nil]
}

svprogresshud not showing in xcode5 ios7

I am trying to use SVProgressHUD with cocoapods. I have install it in my xcode workspace following numerous tutorials online. It seems simple enough to use, but I cannot get it to work. Here my code to load data from rottentomatoes app. I want to show "loading" while the network request is doing its thing. I am wondering if this is ui thread issue ? I added a sleep inside the network request because the results were coming back too fast !
- (void) reload{
[SVProgressHUD showWithStatus:#"Updating" maskType:SVProgressHUDMaskTypeBlack];
NSString *url = #"http://api.rottentomatoes.com/api/public/v1.0/lists/dvds/top_rentals.json?";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
[NSThread sleepForTimeInterval:3];
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[object objectForKey:#"movies"]];
self.movies = [[NSMutableArray alloc]init];
for(NSDictionary *item in array){
SFMovie *movie = [[SFMovie alloc]initWithDictionary:item];
[self.movies addObject:movie];
}
[SVProgressHUD dismiss];
[self.tableView reloadData];
}];
}
EDIT for comment:
The reload is called on both init methods (since I am using storyboard for this project)
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
[self reload];
}
return self;
}
- (id) initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if(self){
[self reload];
}
return self;
}
Second EDIT:
I added a pull down to refresh and the "updating ..." shows up when I pull the tableview down. But it does not show up on init.
- (void)viewDidLoad
{
[super viewDidLoad];
UIRefreshControl *refreshControl = [UIRefreshControl new];
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:#"Pull to refresh..."];
self.refreshControl = refreshControl;
}
- (void)refresh:(UIRefreshControl *)sender{
[self reload];
[sender endRefreshing];
}
So I guess I cannot run UI stuff on init methods as the view is not ready. I am now calling the reload method on viewdidload and it works file. Thank you John !
In any init methods, messing with the view hierarchy is tricky business -- keep that logic in viewDidLoad to avoid any of those modifications from being wiped (especially from storyboard initialization).

passing NSURL and keeping it

I am passing a NSURL from my pickerviewcontroller to my mainviewcontroller. The url is dependent on the user choice in pickerviewcontroller. It works fine, but the user has to repetedly go to the pickerviewcontroller every time the app is restarted to make the choice.
Maybe the code will explain the problem better: This is the pickerviewcontrollers relevant parts...
//The save button on the pickerviewcontroller
- (IBAction)selectedRow:(id)sender {
MainViewController *vc1 = [self.storyboard
instantiateViewControllerWithIdentifier:#"webview"];
vc1.destinationweb = selectedRow;
[self presentViewController:vc1 animated:YES completion:nil];
Once in MainViewController the destinationweb log shows the address of the user choice in pickerview. But If I turn off the app or go forwards in the app (I have another view controller) and then back to MainViewController - it shows destinationweb = null
This is the MainViewController relevant parts:
- (void)viewDidLoad {
{
//webView.hidden = YES;
self.webView.delegate = self;
NSURL *url = destinationweb;
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
NSLog(#"destinationweb shows= %#", destinationweb);
}
[super viewDidLoad];
}
I have no idea what I am supposed to do to make the MainViewController remember the url until another row in picker view is selected??
Just save the url string in user defaults and retrieve the url string in view controller
- (IBAction)selectedRow:(id)sender
{
MainViewController *vc1 = [self.storyboard
instantiateViewControllerWithIdentifier:#"webview"];
//Instead of passing it just save the url string in user defaults
NSString *urlString = [selectedRow absoluteString];
[[NSUserDefaults standardUserDefaults] setObject:urlString forKey:#"UserURL"];
//vc1.destinationweb = selectedRow;
[self presentViewController:vc1 animated:YES completion:nil];
}
- (void)viewDidLoad
{
[super viewDidLoad];
//webView.hidden = YES;
self.webView.delegate = self;
NSString *urlString = [[NSUserDefaults standardUserDefaults] stringForKey:#"UserURL"];
NSURL *url = [NSURL URLWithString:urlString ];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
NSLog(#"destinationweb shows= %#", destinationweb);
}
if you want to keep the value once the app is restarded, you should storage the value (url) in a file, so when you restart it you can read it from there.

Add SubView (WebView) within NSView subclass

OK, the scenario is pretty straightforward, but - since NSViews have never been my strongest point - I decided to ask for some help.
So...
We have an NSView subclass
When the NSView is created, we want to add a subview (WebView) which is going to occupy all the initial view's space + automatically resize in width/height.
And this is my code (which still does not work, as described) :
- (id) initWithFrame:(NSRect)frame {
NSLog(#"In INIT");
self = [super initWithFrame:frame];
if (self == nil) return nil;
[self setWebView:[[WebView alloc] initWithFrame:frame]];
[[self webView] setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
NSString *path = [[NSBundle mainBundle] pathForResource:#"index"
ofType:#"html"];
NSString *htmlContent = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:nil];
[[[self webView] mainFrame] loadHTMLString:htmlContent
baseURL:[NSURL URLWithString:path]];
[self addSubview:[self webView]];
return self;
}
Any ideas?

Display a webpage inside a UIWebView

I try to display a simple webpage inside my UIWebView without a Nib. The problem is when I click on my buttun a new page blanck page appear but nothing is display.
Did I miss something?
- (void)loadView {
UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
self.webView = web;
NSString *urlAddress = #"http://www.google.com";
NSURL *url = [[[NSURL alloc] initWithString:urlAddress] autorelease];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[topView addSubview:self.webView];
[web release];
}
thank you,
If this is the exact code you're using then it can't work: the webView added to topView that is never put on screen anywhere.
You probably want to add the webView to the controller view, but a better place to do that might be viewDidLoad, where self.view can be used safely.
This code works for me:
- (void)viewDidLoad {
[super viewDidLoad];
self.webView = [[[UIWebView alloc]
initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
NSString *urlAddress = #"http://www.google.com";
NSURL *url = [[[NSURL alloc] initWithString:urlAddress] autorelease];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:requestObj];
[self.view addSubview:self.webView];
}
Using the Storyboard -
Step 1: Drag and drop a UIWebView in the View
Step 2: Then go to the .h file (for that particular view) and create an IBOutlet of a UIWebView. For example-
// MainViewController.h
#interface MainViewController : UIViewController
#property (nonatomic, strong) IBOutlet UIWebView *myWebView;
#end
Step 3: Go to the storyboard and create a connection from outlet, myWebView (This can be found in the inspector area of Xcode) to the UIWebView by doing a control drag.
Step 4: Now when we have the connection, we just need to go to the .m (for that particular view) and add the following code -
//MainViewController.m
#implementation MainViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlNameInString = #"https://www.google.com";
NSURL *url = [NSURL URLWithString:urlNameInString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[self.myWebView loadRequest:urlRequest];
}
#end
Here is My Solution.
Create a ViewController with WebView in Interface Builder and connect webview as IBOutlet
This code is simple and works fine
- (void)viewDidLoad
{
[super viewDidLoad];
NSURLRequest *request = [NSURLRequest requestWithURL:#"http://www.google.com.ua"];
[webView loadRequest:request];
}