Tap Detecting Window and Two View Controllers - uiwebview

I'm rather new to iOS development and for my first real app I'm using a TapDetectingWindow to detect touches on a UIWebView (exactly as detailed on http://mithin.in/2009/08/26/detecting-taps-and-events-on-uiwebview-the-right-way).
I used it in one View Controller as suggested with a reference in the header file and the following in the implementation file;
- (void)viewDidLoad {
[super viewDidLoad];
mWindow = (TapDetectingWindow *)[[UIApplication sharedApplication].windows objectAtIndex:0];
mWindow.viewToObserve = igWeb;
mWindow.controllerThatObserves = self;
- (void)userDidTapWebView:(NSArray *)tapPoint {
}
It worked perfectly.
Now the problem is that I would like to use the TapDetectingWindow in a second View Controller.
I copied the same code from the first view controller (only changing the name of the viewToObserve).
Now, when I run the app. The Tap Detecting window works fine in the first ViewController, then works fine when you go to the second View Controller but when you go back to the first view controller its broken until the view gets loaded again.
Please help.

try something like
-(void)viewWillAppear:(BOOL)animated
{
mWindow.viewToObserve = igWeb;
mWindow.controllerThatObserves = self;
[super viewWillAppear:animated];
}

Related

Branch Universal Deep Link does not display custom view controller elements

So I have a Universal link that leads to a view controller in my app. On that particular view controller I display a couple of images as well as a web view. The webView displays a url chosen by the user. How do I save this custom url so that it is displayed every time someone clicks the link? I think the code to this is under:
#synthesize deepLinkingCompletionDelegate;
-(void)configureControlWithData:(NSDictionary *)data {
NSString *string = data[#"favoriteArticle"];
Alex from Branch.io here:
To accomplish this, you need to do two things.
Step 1
Store the URL of the article you want to load as one of the Branch link custom parameters. Full instructions on how to do that here, but essentially:
BranchUniversalObject *branchUniversalObject = [[BranchUniversalObject alloc] initWithCanonicalIdentifier:#"item/12345"];
branchUniversalObject.title = #"My Content Title";
branchUniversalObject.contentDescription = #"My Content Description";
branchUniversalObject.imageUrl = #"https://example.com/mycontent-12345.png";
[branchUniversalObject addMetadataKey:#"favorite_article" value:#"https://example.com/path/to/article"]; // this is used to route inside the app
[branchUniversalObject addMetadataKey:#"property2" value:#"red"];
BranchLinkProperties *linkProperties = [[BranchLinkProperties alloc] init];
linkProperties.feature = #"sharing";
linkProperties.channel = #"facebook";
[linkProperties addControlParam:#"$desktop_url" withValue:#"https://example.com/path/to/article"]; // this is used for desktop visitors
[linkProperties addControlParam:#"$ios_url" withValue:#"https://example.com/path/to/article"]; // this is used for iOS mobile visitors without the app installed
Step 2
Then when the app opens after a link click, watch for that data key. Again, full instructions, but basically:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// initialize the session, setup a deep link handler
[[Branch getInstance] initSessionWithLaunchOptions:launchOptions
andRegisterDeepLinkHandler:^(NSDictionary *params, NSError *error) {
// start setting up the view controller hierarchy
UINavigationController *navC = (UINavigationController *)self.window.rootViewController;
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *nextVC;
// If the key 'favoriteArticle' is present in the deep link dictionary
// then load the picture screen with the appropriate picture
NSString * favoriteArticle = [params objectForKey:#"favorite_article"];
if (favoriteArticle) {
nextVC = [storyboard instantiateViewControllerWithIdentifier:#"ArticleVC"];
[nextVC setArticleUrl: favoriteArticle];
} else {
nextVC = [storyboard instantiateViewControllerWithIdentifier:#"MainVC"];
}
// navigate!
[navC setViewControllers:#[nextVC] animated:YES];
}];
return YES;
}
After this, in your ArticleVC, retrieve the favoriteArticle value and use it for your webview.
Step 2 (Alternate)
The configureControlWithData method you mentioned is used in the automatic deep link routing implementation. You may be able to adapt this to work with a webview, but I haven't personally tried that. It would look something like this:
#synthesize deepLinkingCompletionDelegate;
- (void)configureControlWithData:(NSDictionary *)data {
NSString *favoriteArticle = data[#"favorite_article"];
// load the webview with the URL stored inside favoriteArticle
}

TableView not reloading after modalview dismissed

I have a page that checks if there is a list of employees on the bundle, and if there is it displays them in a table view. But if there is no list on the bundle it throws up a modal view controller. That then requires someone to login, the login is authenticated and then data is downloaded.
The ModalView is setup to be a delegate of the first page. I can call the delegate method just fine and pass the list, but when the ModalView is dismissed the table does not reload the tableview with the data. If i run the project again it loads the list up in the table view instantly.
Here is the method on the ViewDidLoad of the first page
[self checkLastLoginDate];
[self loadDataIntoArray];
if (currentData && dataLoadedIntoArray) {
NSLog(#"sweet the data is current");
[self createIndexedArray];
}
else{
NSLog(#"Data not loaded and not current");
//push login view
///if ipad do this
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
//the above code was working fine. I am just testing pushing a dynamic xib
LoginViewControlleriPad *loginControlleriPad = [[LoginViewControlleriPad alloc] initWithNibName:#"LoginViewControlleripad" bundle:nil];
loginControlleriPad.modalPresentationStyle = UIModalPresentationFormSheet;
loginControlleriPad.delegate = self;
[self presentModalViewController:loginControlleriPad animated:YES];
[self createIndexedArray];
[loginControlleriPad dismissModalViewControllerAnimated:NO];
[self.tableView reloadData];
}
The first two methods check to make sure the data exists on the bundle and that the last login date is within 15 days.
if it is then I create an IndexedArray and it displays nicely.
If the data is not on the bundle or the date is to old I check the device and use a modal view. The delegates are set and the ModalView Appears.
In the ModalView I use a syncronus and asyncronus request to hit a server for the required information. Then I create the list and pass it back to the first page.
Once the connection is made and we do a little work on the list we save it to the bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:kEMPLOYEE_PLIST];
/////write to file/////
[cleanResults writeToFile:path atomically:YES];
employeeList = [[NSMutableArray alloc ]initWithContentsOfFile:path];
if (employeeList != nil)
{
[delegate passUserInfo:employeeList];
//cant get login view to dismiss
//[self dismissModalViewControllerAnimated:YES];
}
Once I get the list I right it to file and then read it back in. If there is info in the list I call the delegate method.
UPDATE
Here is the delgate method
- (void)passUserInfo: (NSMutableArray *)employeeDataArray
{
employeeData = [[NSMutableArray alloc] initWithArray:employeeDataArray];
[self.tableView reloadData];
/////FIX////////
[createIndexedArray];
}
Once that is called nothing happens. I tried dismissing the modal view, which works, but then the first page does not refresh and my app gets lost in the oblivion. I am just confused at were it is going and how i can refresh the tableview on the first page.
Is there a step I are missing? I have tried tracking it and lose it after this step.
I actually figured out that my code was setup right, i just needed to call a method that sorted the array into an alphabetic array. Once i called that method from the delegate method it worked like a snake charm.
UPDATE
I had a method that created an indexed array. When i called that inside the delegate method it reloaded the page and inserted the new into the table view. I am pretty sure it was reloading the whole time, i was just not calling the method that was populating the array that was being being displayed in the tableview.

Presenting UITabBarController Modally - Autorotate Problem

I'm attempting to present a UITabBarController modally using the following code:
// Declare all view controllers.
TabOne *tabOne = [[TabOne alloc] initWithNibName:#"TabOne" bundle:nil];
TabTwo *tabTwo = [[TabTwo alloc] init];
TabThree *tabThree = [[TabThree alloc] init];
// Set each view controller's delegate to self.
tabOne.delegate = self;
tabTwo.delegate = self;
tabThree.delegate = self;
// Set a title for each view controller.
tabOne.title = #"One";
tabTwo.title = #"Two";
tabThree.title = #"Three";
// Create a tab bar controller.
UITabBarController *tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:[NSArray arrayWithObjects:tabOne,tabTwo,tabThree, nil]];
// Present the tab bar controller modally.
[self presentModalViewController:tabBarController animated:NO];
// Memory management.
[tabOne release];
[tabTwo release];
[tabThree release];
This all works as expected except that I get the following warnings in the console:
Using two-stage rotation animation. To use the smoother single-stage animation, this application must remove two-stage method implementations.
Using two-stage rotation animation is not supported when rotating more than one view controller or view controllers not the window delegate.
I've done some research on this and have checked that shouldAutorotateToInterfaceOrientation is implemented as follows:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
As far as I can tell, the problem is that the tab bar controller is not the root view controller, but I'm presenting this modal view some way into a deep view hierarchy. It's called from another modal view, which itself is called from a tab bar set in the application delegate.
I know this is a bit of an old chestnut, but it's got me stumped. Any thoughts?
Thanks in advance.
I've had a similar problem.
UITabBarController has some odd behavior with its orientation handling. When setting its orientation, it calls recursively into self.selectedViewController to decide whether to use one-stage or two-stage animation. That seems sensible, but the trouble is self.selectedViewController is initially nil (in particular, if you're displaying the UITabBarController modally for the first time), and that can confuse the controller. Depending on the iOS version, a nil selectedViewController will lead the UITabBarController to believe that one-stage animation is unsupported.
Try this: when you first load / initialize your UITabBarController, add the line
tabBarController.selectedIndex = 0;
I was getting this warning (including serious visual problems: the view controller was switching orientation but the status bar was not), and setting the index this way fixed the problem. The UITabBarController successfully called into its selected view controller, and detected the one-stage animation.

How to "preload" view controller without actually pushing it?

Background:
I've got a free app that is ad-supported. The basic idea is that when the app is launched, ad content (HTML) is downloaded from the server in the background, and only if the download was successful, then the content is being shown.
Previous solution:
I have implemented this successfully in a universal app. Originally, I loaded a NSData variable with an URL, and if it was successful, then I presented a modal view which contained an UIWebView (relevant code is in another question). The problem is that the external assets (images) don't get loaded in the original NSData request, so in a stroke of genius I thought of another way:
New solution:
The new way, and this is what I want help with, is that I'm instantiating the modal view controller (without displaying it yet), and having the web view begin loading the URL directly. When the webViewDidFinishLoad method is called, I fire a notification back to the parent which then performs the presentModalViewController.
Here are the methods which instantiate the view controller and present it modally:
- (void)launchAd
{
if ([ServerCheck serverReachable:#"openx.freewave-wifi.com" hideAlert:YES])
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(presentAdModal) name:#"AdLoaded" object:nil];
AdViewController *adView = [[AdViewController alloc] initWithNibName:nil bundle:nil];
[[adView view] awakeFromNib]; //THIS LINE IS WHAT THIS QUESTION IS ABOUT
navController = [[UINavigationController alloc] initWithRootViewController:adView];
[adView release], adView = nil;
[navController setModalPresentationStyle:UIModalPresentationFormSheet];
[navController setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
[[navController navigationBar] setTintColor:[UIColor colorWithRed:0.94 green:0.00 blue:0.32 alpha:1.00]];
}
else
LogError(#"Not presenting ad.");
}
- (void)presentAdModal
{
LogInfo(#"Presenting advertisement modal.");
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"AdLoaded" object:nil];
[tabBarController presentModalViewController:navController animated:YES];
[navController release];
}
And in the AdView controller:
- (void)webViewDidFinishLoad:(UIWebView *)theWebView
{
LogInfo(#"Ad content did load; we can show it.");
[timeout invalidate], timeout = nil;
[self setTitle:#"From Our Sponsor"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"AdLoaded" object:nil];
}
Now what's above does work. However, it took a long time for me to figure out how to cause the view controller delegate methods in the AdView controller to fire before calling presentModalViewController. I did this by adding [[adView view] awakeFromNib];, but I know this isn't the right way to make this happen.
So, everything above does work beautifully, effectively having the view controller and its UIWebView "preload" before displaying it. I just want to know what I should be doing instead of [[adView view] awakeFromNib]; -- I want to do it the right way.
Or is this right? I guess some folks would say "If it works, then it's right", but I know this isn't true.

How implement splitview for iphone os 4.2?

I have use the custom splitview in the my application.
custom splitview .h file
#interface CustomUISplitViewController :UISplitViewController {
BOOL keepMasterInPortraitMode;
BOOL keepMasterInPortraitMode1;
}
and .m file is
-(void) viewWillAppear:(BOOL)animated {
keepMasterInPortraitMode1=keepMasterInPortraitMode;
if(keepMasterInPortraitMode1 == NO) {
if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
UIViewController* master = [self.viewControllers objectAtIndex:0];
UIViewController* detail = [self.viewControllers objectAtIndex:1];
[self setupPortraitMode:master detail:detail];
}
}
if (self.interfaceOrientation == UIInterfaceOrientationPortrait || self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
UIViewController* master = [self.viewControllers objectAtIndex:0];
UIViewController* detail = [self.viewControllers objectAtIndex:1];
[self setupPortraitMode:master detail:detail];
}
}
}
- (void)setupPortraitMode:(UIViewController*)master detail:(UIViewController*)detail {
//adjust master view
CGRect f = master.view.frame;
f.size.width = 220;
f.size.height = 1024;
f.origin.x = 0;
f.origin.y =0;
[master.view setFrame:f];
//adjust detail view
f = detail.view.frame;
f.size.width = 548;
f.size.height = 1024;
f.origin.x = 221;
f.origin.y = 0;
[detail.view setFrame:f];
}
This works correctly under iOS4.0 but under 4.2 I see only one view when the app runs. What could change between OS versions?
I was having the same issue and I believe this to be an Apple bug (I filed it a month ago with no response from them.) For me, it was specifically the "detail" view that was blank when the app started at orientation UIInterfaceOrientationLandscapeRight (3). It would look like this: http://d.pr/cGcU. This would occur when I restricted one of the two view controllers (say, the RootViewController) to landscape-only:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}
With this in place, the following would occur during the detail view's initialization:
2010-11-15 20:17:47.792 MultipleDetailViews[96250:207] firstDetailViewController willAnimateRotationToInterfaceOrientation: 3 (landscape)
2010-11-15 20:17:47.792 MultipleDetailViews[96250:207] self.view.hidden is: 0
2010-11-15 20:17:47.799 MultipleDetailViews[96250:207] rotating...
2010-11-15 20:17:47.848 MultipleDetailViews[96250:207] firstDetailViewController didRotateFromInterfaceOrientation
2010-11-15 20:17:47.849 MultipleDetailViews[96250:207] self.view.hidden is: 1
For some reason the detail view would mysteriously become hidden during rotation to orientation 3. Until Apple fixes this bug (it doesn't occur in 3.2), my workaround is currently to override the following method in the detail view controller, re-displaying the view after rotation has completed:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
self.view.hidden = NO;
}
EDIT: If your detail view isn't a direct subview of splitViewController.view (e.g. you are using a UINavigationController), you will need to set hidden on the topmost view on the detail side within the UISplitViewController:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
// Make sure you set splitViewController via an outlet or get it via your AppDelegate
for (UIView *splitViewChild in splitViewController.view.subviews)
splitViewChild.hidden = NO;
}
I have had the exact same problem with my applications. I had used the same Subclassing technique to have the Master and Detail visible in both Portrait and Landscape modes. Worked great until 4.2 which, unfortunately I didn't test for when the Beta releases were available.
I recommend trying the excellent MGSplitViewController (http://mattgemmell.com/2010/07/31/mgsplitviewcontroller-for-ipad). It is an open-source implementation of the UISplitViewController. It's only drawback is that it isn't quite as easy to use in Interface Builder, but it includes a sample project. Visually it is identical to UISplitViewController, but adds support for several extras such as dragging the split position at runtime.
Just implement it exactly as your UISplitViewController but add the following line somewhere:
[splitViewController setShowsMasterInPortrait:YES];
This is very similar to the Private API that Apple prohibits using with their version.
//[splitViewController setHidesMasterViewInPortrait:NO]; // Naughty, Naughty, Not allowed by the Apple police

Resources