Mimicking JavaScript’s alert, confirm and prompt in iOS
While some people argue against these functions, I think they are pretty good tools for rapid prototyping. And I really missed them in iOS, so I created similar functions in my iOS projects. Here is how they can be used:
[sourcecode language=”objc”]
// To show a simple message to user
[ETUtils alert:@”Hello world!”];
// To show a confirmation dialog to user
[ETUtils confirm:@”Would you like to copy this item?” successCallback:^{
NSLog(@”User would like to copy this item.”);
} failureCallback:^{
NSLog(@”User isn’t interested in this operation.”);
}];
// To ask user a simple input
[ETUtils prompt:@”Please enter your name:” successCallback:^(NSString *input) {
NSLog(@”User’s name is %@”, input);
} failureCallback:^{
NSLog(@”User has refused to enter anything.”);
}];
[/sourcecode]
While prototyping, these handy functions can save you a lot of time and energy. Here’s the code for them:
[sourcecode language=”objc”]
//
// ETUtils.h
//
// Created by Umar Ashfaq on 4/28/14.
//
typedef void(^ETCallbackBlock)();
typedef void(^ETPromptCallbackBlock)(NSString *input);
@interface ETUtils : NSObject
+ (void) alert:(NSString *) message;
+ (void) confirm:(NSString *) message successCallback:(ETCallbackBlock)success failureCallback:(ETCallbackBlock)failure;
+ (void) prompt:(NSString *) message successCallback:(ETPromptCallbackBlock)success failureCallback:(ETCallbackBlock)failure;
@end
//
// ETUtils.m
//
// Created by Umar Ashfaq on 4/28/14.
//
#import “ETUtils.h”
#import “ETAlertView.h”
@implementation ETUtils
+ (void) alert:(NSString *) message
{
UIAlertView *view = [[UIAlertView alloc] initWithTitle:@”Alert” message:message delegate:nil cancelButtonTitle:@”Okay” otherButtonTitles:nil, nil];
[view show];
}
+(void) confirm:(NSString *) message successCallback:(ETCallbackBlock)success failureCallback:(ETCallbackBlock)failure
{
ETAlertView *view = [[ETAlertView alloc] initWithTitle:@”Confirm” message:message];
[view addButtonWithTitle:@”OK” callback:success];
[view addButtonWithTitle:@”Cancel” callback:failure];
[view show];
}
+ (void) prompt:(NSString *) message successCallback:(ETPromptCallbackBlock)success failureCallback:(ETCallbackBlock)failure
{
ETAlertView *view = [[ETAlertView alloc] initWithTitle:@”Confirm” message:message];
view.alertViewStyle = UIAlertViewStylePlainTextInput;
__weak ETAlertView *weakView = view;
[view addButtonWithTitle:@”OK” callback:^{
success([weakView textFieldAtIndex:0].text);
}];
[view addButtonWithTitle:@”Cancel” callback:failure];
[view show];
}
@end
[/sourcecode]