2

I'm writing application tests and want to check if an UIAlertView is currently shown. That means I don't have a pointer to it and I need to know who is the owner of the shown UIAlertView or on which views stack it can be found.

Gamadril
  • 907
  • 14
  • 32
  • 1
    possible duplicate : [iPhone SDK: check if a UIAlertView is showing](http://stackoverflow.com/questions/2528929/iphone-sdk-check-if-a-uialertview-is-showing) – Seb T. Sep 28 '11 at 07:43
  • Thanks. Checking the application's windows is the solution. Didn't take into account that there are several windows. Checked only the one controlled by app delegate. – Gamadril Sep 28 '11 at 08:16

1 Answers1

8

[UPDATE] Actually the solution below is not working for iOS 7, because the alert views are not bound to a specific window any more. Read here for details: https://stackoverflow.com/a/18703524/942107

Based on KennyTM'm advice in another question Sebastien provided link to, I've created a UIAlertView category with a method returning the UIAlertView if shown to be able to dismiss it programatically.

UIAlertViewAdditions.h:

#import <UIKit/UIKit.h>

@interface UIAlertView (UIAlertViewAdditions)

+ (UIAlertView *) getUIAlertViewIfShown;

@end

UIAlertViewAdditions.m:

#import "UIAlertViewAdditions.h"

@implementation UIAlertView (UIAlertViewAdditions)

+ (UIAlertView *) getUIAlertViewIfShown {
    if ([[[UIApplication sharedApplication] windows] count] == 1) {
        return nil;
    }

    UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    if ([window.subviews count] > 0) {
        UIView *view = [window.subviews objectAtIndex:0];
        if ([view isKindOfClass:[UIAlertView class]]) {
            return (UIAlertView *) view;
        }
    }
    return nil;
}

@end
Community
  • 1
  • 1
Gamadril
  • 907
  • 14
  • 32
  • 1
    I was using this code in my project and now its not working in iOS7 :( – Abdullah Umer Sep 09 '13 at 16:05
  • Try `UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:2];` and `UIView *view = [window.subviews objectAtIndex:1];` However the cleaner way is to check the class names – Gamadril Sep 20 '13 at 08:49