Is there any way to encapsulate UIAlertController within another UIViewController? - ios

I'm fairly new to iOS, so please keep answers clear. I've been toying with encapsulating UIAlertController in another UIViewController to use it as a replacement for UIActionSheet as it's deprecated in iOS 8.
The idea would be a replacement for UIActionSheet that is backward and forward compatible, , call it ImmortalActionSheet for instance.
If the component is used in iOS 8 or greater, it can use UIAlertController, otherwise it would fall back to UIActionSheet. That would make it a backward and forward compatible action sheet to replace many action sheets around an application I'm working with. And yes I need to maintain backward compatibility.
I've prototyped this but for whatever reason, when I present ImmortalActionSheet, the UIAlertController view itself will always show up at the top left (0, 0). No matter if I change the center, it never moves.
-(void) loadView
{
UIView * child = nil;
if ( [UIAlertController class] )
{
UIAlertController * alertController = [UIAlertController alertControllerWithTitle:#"Make Choice!!" message:#"Choose one!" preferredStyle:UIAlertControllerStyleActionSheet];
for (UIAlertAction * action in actions ){
[alertController addAction:action];
}
child = alertController.view;
[self addChildViewController:alertController];
}
self.view = [[UIView alloc] init];
self.view.backgroundColor = [UIColor clearColor];
[self.view addSubview:child];
}

Related

Transition between UIAlertControllers

What I need to do is present an alert controller with a progressBar. Once the download is complete, I need to transition to a secondary alert controller with a Success! message and an "Ok" button for the user to just exit this setup. I have built the alerts separately and they are working well on their own (well the progress bar is kinda working...) but with this code:
I expect that when the progressBar hits 100% the first alert controller will be dismissed and the next alert will show up, but nothing is happenning This is my code:
-(void)settingUpToolsProgressPopUp {
UIAlertController* progressAlert = [UIAlertController alertControllerWithTitle:#"Setting up tools ..." message:#"This could take a few minutes. Make sure to keep your tools near your mobile device." preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:progressAlert animated:YES completion:^{
//Progress bar setup
UIProgressView *progressView;
progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(8.0, 98.0, progressAlert.view.frame.size.width - 16, 100.0)];
[[progressView layer]setCornerRadius:50];
progressView.trackTintColor = [UIColor whiteColor];
progressView.progressTintColor = [UIColor blueColor];
progressNumerator = 1.0;
progressDenominator = 1.0;
currentProgress = (float)(progressNumerator/progressDenominator);
[progressView setProgress: currentProgress animated:YES];
[progressAlert.view addSubview:progressView];
if(currentProgress > 1.0){
[self settingUpToolsProgressPopUp];
} else if(currentProgress == 1.0){
[self dismissViewControllerAnimated:YES completion:nil];
[self successAlertPopUp];
}
}];
}
p.s. I know that the values are hardcoded right now... but regardless of any values I use the transition doesn't happen. I don't have access to the updating values yet, so I can't use other values right now... but I would expect that if I am using 100% value, then the transition would happen anyway?
Can anyone point me int he right direction? Why isn't this code working for transitioning between these controllers?
Thanks so much!
You need to call successAlertPopUp method inside dismissViewControllerAnimated's completion handler:
[self dismissViewControllerAnimated:YES completion:^{
[self successAlertPopUp];
}];

UIAlertController title and message do not appear in Xcode 8.2

The YES and NO buttons function work as expected, the only problem is that the question No GPS hardware use Triangulation? does not appear to inform the user what the alert is about. The application is tabbed.
The entire code for the project including the xcode project files and Info.plist files can be
found on GitHub, in case you want to build or debug it.
The title and message of the UIAlertController do not appear for the following UIAlertController:
- (UIAlertController*) alertUserNoGPSHardware {
UIAlertController *alertToPresent = nil;
NSString* alertTitleString = #"GPS Alert";
NSString* alertMessage = #"No GPS hardware use Triangulation?";
if (!hardwareExistsOnDevice && mustUseGPSHardware) {
alertToPresent = [UIAlertController alertControllerWithTitle: alertTitleString message:alertMessage
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction actionWithTitle:#"YES" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {mustUseGPSHardware = NO;}];
[alertToPresent addAction:yesButton];
UIAlertAction* noButton = [UIAlertAction actionWithTitle:#"NO" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {mustUseGPSHardware = YES;}];
[alertToPresent addAction:noButton];
}
return alertToPresent;
}
I've also tried to embed the above code in the function that calls this library routine. The same problem occurs.
- (void) setLabelWithGPSLatitudeAndLongitudeWithTimeStampData {
NSString *actionString = nil;
if (displayDataModel) {
if (isFirstGpsClick) {
// Call to the DataModel library that receives a pointer UIAlertView object from the GPS library implementation
// If the UIAlertView pointer is nil proceed with the displaying the latitude, longitude and timestamp.
// If the UIAlertView has a value show the alert, the alert should contain a function to update data in the GPS model.
// This will enable the user to approve of using WiFi or Radio triangulation when the GPS is not available.
/*
* BUG - title and message are not appearing in the alert, the buttons in the alert work as expected
* clicking the YES button removes the warning message that there is no GPS hardware and just
* returns the data. Clicking the no message displays displays the warning message every time.
*/
isFirstGpsClick = NO;
UIAlertController* gpsAlert = [displayDataModel provideGPSAlerters];
if (gpsAlert) {
[self presentViewController:gpsAlert animated:NO completion:nil];
return;
}
}
actionString = [displayDataModel provideGPSLocationData];
}
else {
actionString = #"GPS Button Action Failure: Data Model not created";
}
[displayButtonAction setText:actionString];
}
I've also tried moving the embedded code into the following 2 functions
- (void)viewWillLayoutSubviews {
/*
* Get the tab bar height from the Application Delegate so that the total vertical space
* can be calculated.
*/
AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
if (appDelegate) {
UITabBarController *TempTabBar = appDelegate.tabBarController;
if (TempTabBar) {
// Tab Bar Height is larger than myDelegate.tabBarController.tabBar.frame.size.height indicates
tabBarHeight = TempTabBar.tabBar.frame.size.height * 2.5;
}
}
[self setSubViewSizeVariablesBasedOnViewBounds];
[self addButtonAndLabels];
self.view.backgroundColor = [UIColor whiteColor];
}
- (void)viewDidLoad {
[super viewDidLoad];
if (self.displayModelLibraryInitialization) {
NSLog(#"In Objective-C Implementation viewDidLoad - unable to initialize displayModelLibrary");
}
}
When I move the UIAlertController into viewWillLayoutSubviews() or viewDidLoad() I get the black screen, not
the alert and not the buttons and labels that should be there.
This question does not apply because the current problem is in Objective-c and not Swift.
This question does not apply because no textfield is getting updated.
The code does not use alert builder so this question doesn't apply.
Background
I am new to programming in Xcode, iOS, Objective-c and Swift. This is my first iOS project. It was
an interview coding challenge.
OSX - El Capitan
Xcode - Version 8.2 (8C38)
Running in the simulator.
I am only answering this so that it doesn't add to StackOverflow unanswered questions (on CodeReview we would call an unaswered question a zombie).
#DavidH helped provide the answer.
It seems that there are a few minor quirks to the iPhone 7 plus simulator in Xcode 8.2. DavidH was able to see the message in the alert in the iPhone 7 simulator in Xcode 8.3. I switched to the iPhone 7 simulator from the iPhone 7 plus simulator and saw the message in the alert.
This indicates there may not have been a problem in the code and that the iPhone 7 plus simulator in Xcode 8.2 may be buggy.

How can I programmatically dismiss a UIAlertController

I need to programmatically dismiss a UIAlertController that I'm using as a "please wait" message. I can present the alert without problem but when it comes to dismissing the alert, 50% of the time it dismisses and the other 50% it doesn't, forcing me to restart the app just to continue using it. Any ideas how to dismiss the alert with 100% consistency?
//loadingAlert is a UIAlertController declared in the .h file
//present the Alert
loadingAlert = [UIAlertController alertControllerWithTitle:#"Loading..." message:#"Please wait while we fetch locations" preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:loadingAlert animated:YES completion:nil];
//parse JSON file
_listOfAcquisitions = nil;
MNSHOW_NETWORK_ACTIVITY(YES);
NSString *WebServiceURL = [NSString stringWithFormat:#"JSON URL", _search];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSDictionary *dictionary = [JSONHelper loadJSONDataFromURL:WebServiceURL];
dispatch_async(dispatch_get_main_queue(), ^{
_listOfAcquisitions = [NSMutableArray array];
for (NSDictionary *oneEntry in dictionary) {
Acquisitions *acqu = [[Acquisitions alloc] init];
if([oneEntry objectForKey:#"ADDRESS1"] == (NSString *)[NSNull null]){acqu.ADDRESS1 = #"";}
else {acqu.ADDRESS1 = [oneEntry objectForKey:#"ADDRESS1"];}
if([oneEntry objectForKey:#"STATEABBR"] == (NSString *)[NSNull null]){acqu.STATEABBR = #"";}
else {acqu.STATEABBR = [oneEntry objectForKey:#"STATEABBR"];}
if([oneEntry objectForKey:#"TOWN"] == (NSString *)[NSNull null]){acqu.TOWN = #"";}
else {acqu.TOWN = [oneEntry objectForKey:#"TOWN"];}
if([oneEntry objectForKey:#"ZIPCODE"] == (NSString *)[NSNull null]){acqu.ZIPCODE = #"";}
else {acqu.ZIPCODE = [oneEntry objectForKey:#"ZIPCODE"];}
[_listOfAcquisitions addObject:acqu];
}
dispatch_async(dispatch_get_main_queue(), ^{
MNSHOW_NETWORK_ACTIVITY(NO);
[self refreshAnnotations:self];
});
});
});
//finally dismiss the alert...
[loadingAlert dismissViewControllerAnimated:YES completion:nil];
}
I've just been learning how to do this.
So, wherever the alert controller is built, you need to add the action button either to "OK" in default style or "Cancel" in cancel style.
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:#"You made a mistake."
message:#"Pray we don't alter the alert further"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okayAction = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * _Nonnull action) {
[alertController dismissViewControllerAnimated:YES completion:nil];
}];
[alertController addAction:okayAction];
[self presentViewController:alertController animated:YES completion:nil];
There are other UIAlertActionStyle enumerations, such as UIAlertActionStyleCancel which will put a separator space between other actions and UIAlertActionStyleDestructive which will make the font red but will be in line with other UIAlertActions.
Make sure you add in order: standard actions (Okay, Open Camera, Photo Library) and THEN cancel actions.
There's also preferredStyle:UIAlertControllerStyleActionSheet which is used to set up options for the user. I use this to show Camera and Photo Library.
Also, for your specific dismiss action. The reason it's not working is because you are attempting to dismiss it on the background thread. You should ALWAYS dismiss or make UI changes on the foreground thread. This will cause an NSException/crash in the future.
dispatch_async(dispatch_get_main_queue(), ^{
// dismiss your UIAlertController
});
This is how you should be doing it with your specific code:
dispatch_async(dispatch_get_main_queue(), ^{
MNSHOW_NETWORK_ACTIVITY(NO);
[self refreshAnnotations:self];
[loadingAlert dismissViewControllerAnimated:YES completion:nil];
});
});
You have other issues with your code that you should ask others for help about. I am only a junior developer so I'm not sure how to correctly do what you're trying to do but this should help with dismissing.
You might want to look into loading wheels or toast messages that will say "Please wait" or "Loading".
Using a UIAlertController to show a loading message is rather bad taste.
First of all your network call should probably happen in the completion block of the presentViewController. So you don't dismiss it before it has appeared.
Also the nested dispatch_async seems off, since you call dispatch_get_main_queue(line 32) while already within the mainQue(line 13). And if this were to work the dismiss would need to be within the dispatch_async block so that it actually would dismiss.
But more importantly this is kind of a misuse of the UIAlertController API. Those are intended for user input not to Block UI.
You are better of implementing your own custom view subclass.
Or using MBProgressHUD (https://github.com/jdg/MBProgressHUD). There you can use either the MBProgressHUDModeIndeterminate or MBProgressHUDModeText to accomplish what you are trying.
You're creating/starting/dismissing the alert all within the same block, which means both presentViewController:loadingAlert and [loadingAlert dismissViewControllerAnimated: are being called in the same runloop. This is why you're getting unexpected results.
The dismiss needs to be called from a different cycle of the runloop, so having it called in a separate *block is what you want. You're already doing things in different threads using dispatch_async, which execute in discretely separate runloop so the solution for you is to put the dismissViewControllerAnimated: call within the dispatch_async(dispatch_get_main_queue() to ensure that its both called on the main thread for UI updates, and called in a separate run-loop as its presentation.
You could use dismissWithClickedButtonIndex:animated: but it's now deprecated in iOS9. I would use a timer:
// 3 second delay
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:#selector(dismissAlert) userInfo:nil repeats:NO];
- (void) dismissAlert {
[loadingAlert dismissWithClickedButtonIndex:0 animated:YES];
}
Of course, this isn't what UIAlertViews are intended for. You'd be better of using a loading spinner somewhere (UIActivityIndicatorView).

UIAlertView grey out button

I have a UIAlertView with multiple buttons. Is it possible to grey out and disable a button? I want the button to be visible but clear that it can't be pushed. Any suggestions are appreciated.
Make sure that you have enabled the current VC as implementing the <UIAlertViewDelegate> protocol, and then in your VC you could do the following:
- (void)viewDidAppear:(BOOL)animated {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert!" message:#"This is an alert view" delegate:nil cancelButtonTitle:#"Cancel!" otherButtonTitles:#"Off", #"On", nil];
alert.delegate = self;
[alert show];
}
/* UIAlertViewDelegate methods */
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView {
return NO;
}
// Other UIAlertViewDelegate methods...
Now why you would want to show a UIAlertView with a button which didn't have any functionality is a whole different question... :)
I hear of lots of people subclassing UIAlertView, but then I read this comment on Apple's UIAlertView Class Reference page:
Subclassing Notes
The UIAlertView class is intended to be used as-is and does not
support subclassing. The view hierarchy for this class is private and
must not be modified.
i.e. people should not be attempting to modify the elements or behavior of UIAlertView. It's likely that behavior can change in later versions of iOS (e.g. iOS 8 or iOS 7.1 or whatever), breaking their various modifications to UIAlertView.
Anyways, to answer your question: why not try creating your own UIView that you can add as UIAlertView-like subview on top of any of your views? That way, you'd have easy control over both the buttons and their behavior.

iPhone Action Sheet Cancel Button Only Responds to Touch Near Center

I have encountered something like this before, where a button only responds to touches in part of its view. I found a image view with a transparent area was on a higher z-level, which obscured the touches where the overlap occurred. This was due to the button being added as a subview before the obscuring view was added.
In the case of an action sheet, I thought it would be at the highest z-level over anything else. Since the action sheet was just initialized and shown, there is no way that I can see that something is covering the button.
(For what it's worth, I just converted the app into a universal app, and am testing in both iOS 4.3 and 5.0. There is no cancel button in the action sheet on the iPad. This problem exists when simulating for iPhone for both iOS 4.3 and 5.0.)
I'm looking for other ideas as to what is causing the problem.
UPDATE
Here is the code to show the action sheet
- (void) shareButtonPressed {
SHKItem *item = [SHKItem larkspreeSearchResult:searchResult];
item.image = eventImageRaw;
// Get the ShareKit action sheet
SHKActionSheet *actionSheet = [SHKActionSheet actionSheetForItem:item];
// Display the action sheet
[actionSheet showInView:self.view];
}
Since this is for a subclassed action sheet, this, right out of ShareKit, might be helpful, too.
+ (SHKActionSheet *)actionSheetForType:(SHKShareType)type
{
SHKActionSheet *as = [[SHKActionSheet alloc] initWithTitle:SHKLocalizedString(#"Share")
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
as.item = [[[SHKItem alloc] init] autorelease];
as.item.shareType = type;
as.sharers = [NSMutableArray arrayWithCapacity:0];
NSArray *favoriteSharers = [SHK favoriteSharersForType:type];
// Add buttons for each favorite sharer
id class;
for(NSString *sharerId in favoriteSharers)
{
class = NSClassFromString(sharerId);
if ([class canShare])
{
[as addButtonWithTitle: [class sharerTitle] ];
[as.sharers addObject:sharerId];
}
}
// Add More button
[as addButtonWithTitle:SHKLocalizedString(#"More...")];
// Add Cancel button
[as addButtonWithTitle:SHKLocalizedString(#"Cancel")];
as.cancelButtonIndex = as.numberOfButtons -1;
return [as autorelease];
}
The showInView method has not been overridden.
If this view controller is part of a UINavigationController with a toolbar configured or a UITabBarController then any action sheet needs to be presented in the parent controller's view. For instance, [actionSheet showInView:self.navigationController.view]; or [actionSheet showInView:self.tabBarController.view];.

Resources