Second UIWindow Not Displaying (iPad) - cocoa-touch

I am attempting to create two UIWindows because I would like two UINavigationControllers on screen at the same time on my app. I initialize two windows in my app delegate but only one window's view is displayed. Does anyone know why this is so?
Here is the code I used:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIViewController * controller1 = [[UIViewController alloc] init];
[controller1.view setBackgroundColor:[UIColor grayColor]];
UINavigationController * nav1 = [[UINavigationController alloc] initWithRootViewController:controller1];
[window addSubview:nav1.view];
[window makeKeyAndVisible];
UIWindow * window2 = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
UIViewController * controller2 = [[UIViewController alloc] init];
[controller2.view setBackgroundColor:[UIColor yellowColor]];
UINavigationController * nav2 = [[UINavigationController alloc] initWithRootViewController:controller2];
[window2 addSubview:nav2.view];
[window2 makeKeyAndVisible];
NSLog(#"%#", [[UIApplication sharedApplication] windows]);
return YES;
}
The gray from the first window is visible, but the yellow from the second is not. The output from this is:
"<UIWindow: 0x591e650; frame = (0 0; 768 1024); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x591e7a0>>",
"<UIWindow: 0x5923920; frame = (0 0; 100 100); layer = <CALayer: 0x59239a0>>"
which means the second window is created and added to the application, but just not displayed. Does anyone know why this is so?
Thanks in advance!

The two UIWindow's windowLevel property is equal, they are all UIWindowLevelNormal.
If you want the second UIWindow display font of the first UIWindow, You should set the second UIWindow's windowLevel value bigger. Like:
window2.windowLevel = UIWindowLevelNormal + 1;
PS:
[window makeKeyAndVisible];
...
[window2 makeKeyAndVisible];
There is only one keyWindow at a time, The key window is the one that is designated to receive keyboard and other non-touch related events. Only one window at a time may be the key window.

Just use a UISplitViewController.
Or try MGSplitVIewController if you need to customization. It might have what you need.

I've discovered how to get the second UIWindow to display. You must set the clipsToBound property to YES. Otherwise, the view from one of the windows will completely cover the other view. The two windows were properly added and visible after all.

This might be a really old post but I just run into the same problem. Some coding mistakes where already answered but the main issue we have here is how you instantiating the UIWindow.
Here is a Swift example how to display another UIWindow correctly.
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? = UIWindow(frame: UIScreen.mainScreen().bounds)
let newWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
// save a reference to your Window so it won't be released by ARC
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window!.rootViewController = SomeViewController()
self.window!.makeKeyAndVisible()
// in your example you have created the window inside this method,
// which executes correctly and at the end of this method just releases the window,
// because you never saved the reference to the window
self.newWindow.rootViewController = SomeOtherViewController()
self.newWindow.windowLevel = UIWindowLevelStatusBar + 1.0
self.newWindow.hidden = false
return true
}
}
Btw. you don't have to create a UIWindow in AppDelegate. It depends on your code behavior.

try this code...
id delegate = [[UIApplication sharedApplication] delegate];
[[delegate FirstView] presentModalViewController:SecondView animated:YES];

Related

iOS10 SFSafariViewController not working when alpha is set to 0

I'm using SFSafariViewController to grab user's cookie in my app. Here's is my code:
SFSafariViewController *safari = [[SFSafariViewController alloc]initWithURL:[NSURL URLWithString:referrerUrl] entersReaderIfAvailable:NO];
safari.delegate = self;
safari.modalPresentationStyle = UIModalPresentationOverCurrentContext;
safari.view.alpha = 0.0;
safari.view.hidden = true;
[self dismissViewControllerAnimated:false completion:nil];
NSLog(#"[referrerService - StoreViewController] presenting safari VC");
[self presentViewController:safari animated:false completion:nil];
This works well on iOS 9. but on iOS 10 it seems that the SF controller doesn't work (it also block my current context - which happens to be another UIWebView).
Anyone can suggest of an alternative way to hide a SFSafariViewController?
Updated answer:
Apple prohibits this kind of SafariViewController usage in last version of review guidelines:
SafariViewContoller must be used to visibly present information to users; the controller may not be hidden or obscured by other views or layers. Additionally, an app may not use SafariViewController to track users without their knowledge and consent.
Old answer:
In iOS 10 there are some additional requirements for presented SFSafariViewController:
1) Your view should not be hidden, so hidden should be set to NO
2) The minimum value for alpha is 0.05
3) You need to add controller manually with addChildViewController: / didMoveToParentViewController: (callback's doesn't called otherwise).
4) UIApplication.keyWindow.frame and SFSafariViewController.view.frame should have non-empty intersection (in appropriate coordinate space), that means:
safari view size should be greater than CGSizeZero
you can't place safari view off the screen
but you can hide safari view under your own view
Code example:
self.safariVC = [[SFSafariViewController alloc] initWithURL:referrerUrl];
self.safariVC.delegate = self;
self.safariVC.view.alpha = 0.05;
[self addChildViewController:self.safariVC];
self.safariVC.view.frame = CGRectMake(0.0, 0.0, 0.5, 0.5);
[self.view insertSubview:self.safariVC.view atIndex:0];
[self.safariVC didMoveToParentViewController:self];
Also, don't forget to remove safariVC properly after the end of the usage:
[self.safariVC willMoveToParentViewController:nil];
[self.safariVC.view removeFromSuperview];
[self.safariVC removeFromParentViewController];
New info: Don't do this.
The revised App Store guidelines prohibit this practice.
https://developer.apple.com/app-store/review/guidelines/
I'll leave this below for posterity:
I call the following code from my app delegate's didFinishLaunchingWithOptions.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self checkCookie];
}
- (void)checkCookie
{
NSURL *url = [NSURL URLWithString:#"http://domainToCheck.com"];
SFSafariViewController *vc = [[SFSafariViewController alloc] initWithURL:url];
vc.delegate = self;
UIViewController *windowRootController = [[UIViewController alloc] init];
self.secondWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.secondWindow.rootViewController = windowRootController;
[self.secondWindow makeKeyAndVisible];
[self.secondWindow setAlpha:0.1];
[windowRootController presentViewController:vc animated:NO completion:nil];
self.window.windowLevel = 10;
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(nonnull NSDictionary<NSString *,id> *)options
{
[self.secondWindow.rootViewController dismissViewControllerAnimated:NO completion:nil];
self.secondWindow = nil;
self.window.windowLevel = 0;
return YES;
}
I was able to achieve this affect using invisible child view controller:
_safariViewController = [[SFSafariViewController alloc] initWithURL:_requestURL];
_safariViewController.delegate = self;
_safariViewController.view.userInteractionEnabled = NO;
_safariViewController.view.alpha = 0.0;
[_containerViewController addChildViewController:_safariViewController];
[_containerViewController.view addSubview:_safariViewController.view];
[_safariViewController didMoveToParentViewController:_containerViewController];
_safariViewController.view.frame = CGRectZero;
its possible to use this on swift 3 for xcode 8.3.2 becausa i get all i delegate anduse correctly , but i have this error
[12:05]
2017-04-25 12:05:03.680 pruebaslibrary[7476:136239] Warning: Attempt to present on whose view is not in the window hierarchy!

Displaying a Custom UIView on Springboard (Jailbreak)

I created a custom UIView programmatically. Does anyone know what class and what method I would use to display this on the springboard? I want my UIView to display on the springboard, and when a user opens an app I want it to show up there too. I have been searching through the private headers for some time and I can't seem to find what I'm looking for. I am developing a jailbreak tweak with iosopendev. Also could you tell me if the class is a viewcontroller or just a view?
If you want the UIView to show anywhere (on SpringBoard and in apps), you should create a new UIWindow above the others and show your view in it like this :
UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
window.windowLevel = UIWindowLevelAlert + 2;
[window setHidden:NO];
[window setAlpha:1.0];
[window setBackgroundColor:[UIColor clearColor]];
[window addSubview:yourView];
You can hook some methods of SpringBoard such as :
- (void)applicationDidFinishLaunching:(id)arg1
And then, your code should be like this :
- (void)applicationDidFinishLaunching:(id)arg1
{
%orig;
NSLog(#"----- applicationDidFinishLaunching -----");
UIWindow *_uiwindow = [[UIWindow alloc] initWithFrame:CGRectMake(100,100,120,100)];
_uiwindow.windowLevel = UIWindowLevelStatusBar;
_uiwindow.hidden = NO;
[_uiwindow setBackgroundColor:[UIColor redColor]];
}
To add more custom views,just add subview to _uiwindow. Hope that will help you.

ModalViewController for Single Subview

Ok, so bear with me: as this is an Objective-C related question, there's obviously a lot of code and subclassing. So here's my issue. Right now, I've got an iPad app that programmatically creates a button and two colored UIViews. These colored UIViews are controlled by SubViewControllers, and the entire thing is in a UIView controlled by a MainViewController. (i.e. MainViewController = [UIButton, SubViewController, SubViewController])
Now, all of this happens as it should, and I end up with what I expect (below):
However, when I click the button, and the console shows "flipSubView1", nothing happens. No modal view gets shown, and no errors occur. Just nothing. What I expect is that either subView1 or the entire view will flip horizontally and show subView3. Is there some code that I'm missing that would cause that to happen / is there some bug that I'm overlooking?
viewtoolsAppDelegate.m
#implementation viewtoolsAppDelegate
#synthesize window = _window;
#synthesize mvc;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
mvc = [[MainViewController alloc] initWithFrame:self.window.frame];
[self.window addSubview:mvc.theView];
[self.window makeKeyAndVisible];
return YES;
}
MainViewController.m
#implementation MainViewController
#synthesize theView;
#synthesize subView1, subView2, subView3;
- (id)initWithFrame:(CGRect) frame
{
theView = [[UIView alloc] initWithFrame:frame];
CGRect sV1Rect = CGRectMake(frame.origin.x+44, frame.origin.y, frame.size.width-44, frame.size.height/2);
CGRect sV2Rect = CGRectMake(frame.origin.x+44, frame.origin.y+frame.size.height/2, frame.size.width-44, frame.size.height/2);
subView1 = [[SubViewController alloc] initWithFrame:sV1Rect andColor:[UIColor blueColor]];
subView2 = [[SubViewController alloc] initWithFrame:sV2Rect andColor:[UIColor greenColor]];
subView3 = [[SubViewController alloc] initWithFrame:sV1Rect andColor:[UIColor redColor]];
[theView addSubview:subView1.theView];
[theView addSubview:subView2.theView];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton addTarget:self action:#selector(flipSubView1:) forControlEvents:(UIControlEvents)UIControlEventTouchDown];
[aButton setFrame:CGRectMake(0, 0, 44, frame.size.height)];
[theView addSubview:aButton];
return self;
}
- (void)flipSubView1:(id) sender
{
NSLog(#"flipSubView1");
[subView3 setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[subView1 presentModalViewController:subView3 animated:YES];
}
SubViewController.m
#implementation SubViewController
#synthesize theView;
- (id)initWithFrame:(CGRect)frame andColor:(UIColor *)color
{
theView = [[UIView alloc] initWithFrame:frame];
theView.backgroundColor = color;
return self;
}
TLDR: modal view not working. should see flip. don't.
It doesn't look like you're setting the 'view' property of the MainViewController anywhere, just 'theView'. The controllers view delegate must be connected to the root view it displays for it to work properly. You'll need to correct that on the Sub View Controller impl as well. If you want all the plumbing that framework classes bring, you have to set things up the way they expect.
Also, you're calling presentModalViewController on one of the sub view controllers; change that to call [self presentModalViewController:...], since the MainViewController is the one which will 'own' the modal view.
I think if you fix those points, you'll find -presentModalViewController will work.

Getting reference to the top-most view/window in iOS application

I'm creating a reusable framework for displaying notifications in an iOS application. I'd like the notification views to be added over the top of everything else in the application, sort of like a UIAlertView. When I init the manager that listens for NSNotification events and adds views in response, I need to get a reference to the top-most view in the application. This is what I have at the moment:
_topView = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
Would this work for any iOS application or is their a safer/better way to get the top view?
Whenever I want to display some overlay on top of everything else, I just add it on top of the Application Window directly:
[[[UIApplication sharedApplication] keyWindow] addSubview:someView]
There are two parts of the problem: Top window, top view on top window.
All the existing answers missed the top window part. But [[UIApplication sharedApplication] keyWindow] is not guaranteed to be the top window.
Top window. It is very unlikely that there will be two windows with the same windowLevel coexist for an app, so we can sort all the windows by windowLevel and get the topmost one.
UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {
return win1.windowLevel - win2.windowLevel;
}] lastObject];
Top view on top window. Just to be complete. As already pointed out in the question:
UIView *topView = [[topWindow subviews] lastObject];
Usually that will give you the top view, but there's no guarantee that it's visible to the user. It could be off the screen, have an alpha of 0.0, or could be have size of 0x0 for example.
It could also be that the keyWindow has no subviews, so you should probably test for that first. This would be unusual, but it's not impossible.
UIWindow is a subclass of UIView, so if you want to make sure your notification is visible to the user, you can add it directly to the keyWindow using addSubview: and it will instantly be the top most view. I'm not sure if this is what you're looking to do though. (Based on your question, it looks like you already know this.)
Actually there could be more than one UIWindow in your application. For example, if a keyboard is on screen then [[UIApplication sharedApplication] windows] will contain at least two windows (your key-window and the keyboard window).
So if you want your view to appear ontop of both of them then you gotta do something like:
[[[[UIApplication sharedApplication] windows] lastObject] addSubview:view];
(Assuming lastObject contains the window with the highest windowLevel priority).
I'm sticking to the question as the title states and not the discussion. Which view is top visible on any given point?
#implementation UIView (Extra)
- (UIView *)findTopMostViewForPoint:(CGPoint)point
{
for(int i = self.subviews.count - 1; i >= 0; i--)
{
UIView *subview = [self.subviews objectAtIndex:i];
if(!subview.hidden && CGRectContainsPoint(subview.frame, point))
{
CGPoint pointConverted = [self convertPoint:point toView:subview];
return [subview findTopMostViewForPoint:pointConverted];
}
}
return self;
}
- (UIWindow *)topmostWindow
{
UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {
return win1.windowLevel - win2.windowLevel;
}] lastObject];
return topWindow;
}
#end
Can be used directly with any UIWindow as receiver or any UIView as receiver.
If you are adding a loading view (an activity indicator view for instance), make sure you have an object of UIWindow class. If you show an action sheet just before you show your loading view, the keyWindow will be the UIActionSheet and not UIWindow. And since the action sheet will go away, the loading view will go away with it. Or that's what was causing me problems.
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if (![NSStringFromClass([keyWindow class]) isEqualToString:#"UIWindow"]) {
// find uiwindow in windows
NSArray *windows = [UIApplication sharedApplication].windows;
for (UIWindow *window in windows) {
if ([NSStringFromClass([window class]) isEqualToString:#"UIWindow"]) {
keyWindow = window;
break;
}
}
}
If your application only works in portrait orientation, this is enough:
[[[UIApplication sharedApplication] keyWindow] addSubview:yourView]
And your view will not be shown over keyboard and status bar.
If you want to get a topmost view that over keyboard or status bar, or you want the topmost view can rotate correctly with devices, please try this framework:
https://github.com/HarrisonXi/TopmostView
It supports iOS7/8/9.
Just use this code if you want to add a view above of everything in the screen.
[[UIApplication sharedApplication].keyWindow addSubView: yourView];
try this
UIWindow *window = [[[UIApplication sharedApplication] windows] lastObject];
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if (![NSStringFromClass([keyWindow class]) isEqualToString:#"UIWindow"]) {
NSArray *windows = [UIApplication sharedApplication].windows;
for (UIWindow *window in windows) {
if ([NSStringFromClass([window class]) isEqualToString:#"UIWindow"]) {
keyWindow = window;
break;
}
}
}

UISplitViewController programmatically without nib/xib

I usually create my projects without IB-stuff. The first thing I do is to strip off all references to xibs, outlets updated plist, etc and so forth. No problems, works great (in my world)!
Now, I just installed 3.2 and tried to develop my first iPad app. Following same procedure as before, I created a UISplitView-based application project and stripped off all IB-stuff. Also, I followed the section in Apple's reference docs: Creating a Split View Controller Programmatically, but nevertheless, the Master-view is never shown, only the Detail-view is (no matter what the orientation is). I really have tried to carefully look this through but I cannot understand what I have missed.
Is there a working example of a UISplitViewController without the nibs floating around somewhere? I have googled but could not find any. Or do you know what I probably have missed?
Declare your splitviewcontroller in your delegate header, use something like this in your didfinishlaunching
ensure you add the UISplitViewControllerDelegate to the detailedViewController header file and that you have the delegate methods aswell. remember to import relevant header files
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
splitViewController = [[UISplitViewController alloc] init];
rootViewController *root = [[rootViewController alloc] init];
detailedViewController *detail = [[detailedViewController alloc] init];
UINavigationController *rootNav = [[UINavigationController alloc] initWithRootViewController:root];
UINavigationController *detailNav = [[UINavigationController alloc] initWithRootViewController:detail];
splitViewController.viewControllers = [NSArray arrayWithObjects:rootNav, detailNav, nil];
splitViewController.delegate = detail;
[window addSubview:splitViewController.view];
EDIT - as per Scott's excellent suggestion below, don't add to the windows subview, instead
[self.window setRootViewController:(UIViewController*)splitViewController]; // that's the ticket
[window makeKeyAndVisible];
return YES;
}
//detailedView delegate methods
- (void)splitViewController:(UISplitViewController*)svc
willHideViewController:(UIViewController *)aViewController
withBarButtonItem:(UIBarButtonItem*)barButtonItem
forPopoverController:(UIPopoverController*)pc
{
[barButtonItem setTitle:#"your title"];
self.navigationItem.leftBarButtonItem = barButtonItem;
}
- (void)splitViewController:(UISplitViewController*)svc
willShowViewController:(UIViewController *)aViewController
invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
self.navigationItem.leftBarButtonItem = nil;
}
I also prefer code to IB ;-)
Oldish thread, but thought I'd spare reader time + grief when the above technique fails to produce a UISplitViewController that responds correctly to device orientation change events. You'll need to:
Ensure all subordinate views respond properly in
shouldAutorotateToInterfaceOrientation. Nothing new here.
Rather than add the UISplitViewController's view to the main window,
[window addSubview:splitViewController.view]; // don't do this
instead set the main window's root controller to the UISplitViewController:
[self.window setRootViewController:(UIViewController*)splitViewController]; // that's the ticket
Adding the splitviewcontroller's view as a subview of the main window (barely) allows it to co-present with sibling views, but it doesn't fly with UISplitViewController's intended use case. A UISplitViewController is a highlander view; there can only be one.
Swift 5.2
iOS 13
Both master and detail view controllers are embedded in navigation controllers
let splitViewController = UISplitViewController()
splitViewController.delegate = self
let masterVC = MasterViewController()
let detailVC = DetailViewController()
let masterNavController = UINavigationController(rootViewController: masterVC)
let detailNavController = UINavigationController(rootViewController: detailVC)
splitViewController.viewControllers = [masterNavController,detailNavController]
You can put this code in your AppDelegate's (or in SceneDelegate if your target is iOS 13.0+)didFinishLaunchingWithOptions function. Just remember to make the splitViewController your rootViewController like this
self.window!.rootViewController = splitViewController
I had just met the same problem.
make sure that your child viewController of splitview can Autorotate to interface orientation.
you can change the function in your childViewController like this:
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
then the master view will be shown.