Technology: Objective-C, xCode 7
#property (nonatomic, copy) NSString *notes;
#synthesize notes;
example.notes = #"Click <a href='http://www.google.com'>here</a>";
NSString *msg = [#"" stringByAppendingFormat:#"%#", myAnnotation.notes];
UIAlertController *alertViewController = [UIAlertController alertControllerWithTitle: #"Title of Alert Box" message: msg preferredStyle: UIAlertControllerStyleAlert];
[alertViewController addAction: [UIAlertAction actionWithTitle: #"Close" style: UIAlertActionStyleCancel handler: nil]];
[self presentViewController: alertViewController animated: YES completion: nil];
Trying to get a link to appear in the Alert Box, but having no luck. Just outputs as plain text.
Is this even possible? If so, using my example above, how would you implement it?
Just like this.
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Alert Title"
message:msg
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"GO"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSString *urlString = #"someurl.com";
NSURL *url = [NSURL URLWithString:urlString];
if (NSClassFromString(#"SFSafariViewController"))
{
SFSafariViewController *safariViewController = [[SFSafariViewController alloc]initWithURL:url];
safariViewController.delegate = self;
[self presentViewController:safariViewController animated:YES completion:nil];
}
else
{
if ([[UIApplication sharedApplication] canOpenURL:url])
{
[[UIApplication sharedApplication] openURL:url];
}
}
}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
I've added code for opening link in SFSafariController only for iOS 9. In iOS 8 devices, it will open with safari browser as SFSafariController does not exist in iOS 8. This is done because apple now considers it bad user experience to exit the app to go to external links. So you can either open links in a web view or Safari Controller.
Related
I have a button to share my app's link. I want a dialog box for it. I have searched a lot for it but haven't found a satisfactory solution. How can I share my application link to different social platforms, like Facebook, Twitter or Gmail?
I'm using this code:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *textToShare = #"Look at this awesome website for aspiring iOS Developers!";
NSURL *myWebsite = [NSURL URLWithString:#"My URL"];
NSArray *objectsToShare = #[textToShare, myWebsite];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
NSArray *excludeActivities = #[UIActivityTypePostToFacebook,
UIActivityTypePostToTwitter,
UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo];
activityVC.excludedActivityTypes = excludeActivities;
[self presentViewController:activityVC animated:YES completion:nil];
// Do any additional setup after loading the view.
}
You can create your Share Action Button directly from Interface Builder and ctrl drag it into your code.
Then you can do something like this :
- (IBAction)shareByFacebook:(id)sender {
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[self generateMessage:controller];
}else{
UIAlertView* facebookAlert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(#"Social.Account.FB.title", #"") message:NSLocalizedString(#"Social.Account.FB.message", #"") delegate:nil cancelButtonTitle:NSLocalizedString(#"Error.ok", #"") otherButtonTitles: nil];
[facebookAlert show];
}
}
This method share an image and a corresponding text message to Facebook.
- (IBAction)shareByTwitter:(id)sender {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
[self generateMessage:tweetSheet];
}else{
UIAlertView* twitterAlert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(#"Social.Account.Twitter.title", #"") message:NSLocalizedString(#"Social.Account.Twitter.message", #"") delegate:nil cancelButtonTitle:NSLocalizedString(#"Error.ok", #"") otherButtonTitles: nil];
[twitterAlert show];
}
}
Same for Twitter.
Don't forget to import #import <Social/Social.h>
I have created a generic generateMessage method in order to avoid code repetition.
-(void)generateMessage:(SLComposeViewController *)controller
{
if ([controller.serviceType isEqualToString:SLServiceTypeTwitter]) {
NSString* message = #"The message you want."
[controller setInitialText:message];
}
[controller setCompletionHandler:^(SLComposeViewControllerResult result) {
if (result == SLComposeViewControllerResultDone) {
DDLogInfo(#"Posted");
} else if (result == SLComposeViewControllerResultCancelled) {
DDLogInfo(#"Post Cancelled");
} else {
DDLogInfo(#"Post Failed");
}
}];
[self.parentVC presentViewController:controller animated:YES completion:nil];
}
Those methods enable you to share content (images, photos, message..) to your Facebook/Twitter and Google account directly from your app.
N.B: For Google it's a little bit different because their share method is now deprecated
Share Google+ iOS
But you can use the old way, like this example in order to share an URL for example :
- (void)showGooglePlusShare:(NSURL*)shareURL {
// Construct the Google+ share URL
NSURLComponents* urlComponents = [[NSURLComponents alloc]
initWithString:#"https://plus.google.com/share"];
urlComponents.queryItems = #[[[NSURLQueryItem alloc]
initWithName:#"url"
value:[shareURL absoluteString]]];
NSURL* url = [urlComponents URL];
if ([SFSafariViewController class]) {
// Open the URL in SFSafariViewController (iOS 9+)
SFSafariViewController* controller = [[SFSafariViewController alloc]
initWithURL:url];
controller.delegate = self;
[self.parentVC presentViewController:controller animated:YES completion:nil];
} else {
// Open the URL in the device's browser
[[UIApplication sharedApplication] openURL:url];
}
}
EDIT :
You can create only 1 IBAction button in order to share to social network.
And then the user has to choose which one.
The result will be something like this :
And the code example :
- (IBAction)shareContentSocialNetwork:(id)sender
{
if ([UIAlertController class]){
// ios 8 or higher
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"" message:#"Share on Social Network" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction* fb = [UIAlertAction actionWithTitle:#"Facebook" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
// Create a method in order to add image, text etc..
[self generateMessage:controller];
}else{
UIAlertView* facebookAlert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(#"Social.Account.FB.title", #"") message:NSLocalizedString(#"Social.Account.FB.message", #"") delegate:nil cancelButtonTitle:NSLocalizedString(#"Error.ok", #"") otherButtonTitles: nil];
[facebookAlert show];
}
}];
[alertController addAction:fb];
UIAlertAction* twit = [UIAlertAction actionWithTitle:#"Twitter" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
// Create a method in order to add image, text etc..
[self generateMessage:controller];
}else{
UIAlertView* twitterAlert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(#"Social.Account.Twitter.title", #"") message:NSLocalizedString(#"Social.Account.Twitter.message", #"") delegate:nil cancelButtonTitle:NSLocalizedString(#"Error.ok", #"") otherButtonTitles: nil];
[twitterAlert show];
}
}];
[alertController addAction:twit];
UIAlertAction* ggl = [UIAlertAction actionWithTitle:#"Google+" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
NSURL *url = [[NSURL alloc] initWithString:#"yourContentURL"];
[self showGooglePlusShare:url];
}];
[alertController addAction:ggl];
UIAlertAction* cancel = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:cancel];
[self presentViewController:alertController animated:YES completion:nil];
}
}
Basically I am creating the 3 specific actions of the AlertController.
For Twitter and Facebook it is pretty straightforward, even so you have to use the generateMessage method I showed you earlier.
Hope it helps.
I have tried several ways to use UIAlertController,instead of UIAlertView. I tried several ways but I cannot make the alert action work.
Here is my code that works fine in IOS 8 and IOS 9 but is showing up with deprecated flags. I tried the elegant suggestion below but I can't make it function in this context. I need to submit my app and this is the last thing to address. Thank You for any further suggestions. I am a newbie.
#pragma mark - BUTTONS ================================
- (IBAction)showModesAction:(id)sender {
NSLog(#"iapMade: %d", iapMade3);
// IAP MADE ! ===========================================
if (!iapMade3) {
//start game here
gamePlaysCount++;
[[NSUserDefaults standardUserDefaults]setInteger:gamePlaysCount forKey:#"gamePlaysCount"];
NSLog(#"playsCount: %ld", (long)gamePlaysCount);
if (gamePlaysCount >= 4) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Basic"
message: THREE_PLAYS_LIMIT_MESSAGE
delegate:self
cancelButtonTitle:#"Yes, please"
otherButtonTitles:#"No, thanks", nil];
[alert show];
NSString *path = [[NSBundle mainBundle] pathForResource:#"cow" ofType:#"wav"];
_pop =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[_pop play];
[self dismissViewControllerAnimated:true completion:nil];
} else {
if (gamePlaysCount == 1) {
// Create & store the next 5 mins when player gets 3 more lives
nextDateToPlay = [[NSDate date] dateByAddingTimeInterval:60*60*0.1];
NSLog(#"CURRENT DATE: %#", [NSDate date]);
NSLog(#"NEXT DAY: %#", nextDateToPlay);
[[NSUserDefaults standardUserDefaults]setObject: nextDateToPlay forKey:#"nextDateToPlay"];
NSLog(#"nextDateToPlay: %#", nextDateToPlay);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Basic"
message: THREE_PLAYS_LIMIT_MESSAGE2
delegate:self
cancelButtonTitle:#"Got it!"
otherButtonTitles:#"Start", nil];
[alert show];
} else {
if (gamePlaysCount == 3) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Basic"
message: THREE_PLAYS_LIMIT_MESSAGE3
delegate:self
cancelButtonTitle:#"Yep, I Know!"
otherButtonTitles:#"Start", nil];
[alert show];
}
}
}
}
}
// IAP NOT MADE =============================
#pragma mark - ALERTVIEW DELEGATE ============================
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if ([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:#"Yes, please"]) {
UIStoryboard *storyboard = self.storyboard;
MenuViewController *svc = [storyboard instantiateViewControllerWithIdentifier:#"Store"];
svc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentViewController:svc animated:YES completion:nil];
}
}
From iOS8 Apple provide new UIAlertController class which you can use instead of UIAlertView which is now deprecated, it is also stated in deprecation message:
UIAlertView is deprecated. Use UIAlertController with a preferredStyle
of UIAlertControllerStyleAlert instead
So you should use something like this
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#"Title"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:#"Yes, please"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Handle your yes please button action here
}];
UIAlertAction* noButton = [UIAlertAction
actionWithTitle:#"No, thanks"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Handle no, thanks button
}];
[alert addAction:yesButton];
[alert addAction:noButton];
[self presentViewController:alert animated:YES completion:nil];
//Calling
[self showMessage:#"There is no internet connection for this device"
withTitle:#"Error"];
//Method
-(void)showMessage:(NSString*)message withTitle:(NSString *)title
{
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
}];
[alert addAction:okAction];
UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[vc presentViewController:alert animated:YES completion:nil];
}
If you want to use this alert in NSObject class you should use like:
-(void)showMessage:(NSString*)message withTitle:(NSString *)title{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alertController animated:YES completion:^{
}];
});
}
Swift version of new implementation is :
let alert = UIAlertController(title: "Oops!", message:"your message", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay.", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
Xcode 8 + Swift
Assuming self is a UIViewController:
func displayAlert() {
let alert = UIAlertController(title: "Test",
message: "I am a modal alert",
preferredStyle: .alert)
let defaultButton = UIAlertAction(title: "OK",
style: .default) {(_) in
// your defaultButton action goes here
}
alert.addAction(defaultButton)
present(alert, animated: true) {
// completion goes here
}
}
Make UIAlertController+AlertController Category as:
UIAlertController+AlertController.h
typedef void (^UIAlertCompletionBlock) (UIAlertController *alertViewController, NSInteger buttonIndex);
#interface UIAlertController (AlertController)
+ (instancetype)showAlertIn:(UIViewController *)controller
WithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitle
tapBlock:(UIAlertCompletionBlock)tapBlock;
#end
UIAlertController+AlertController.m
#implementation UIAlertController (NTAlertController)
+ (instancetype)showAlertIn:(UIViewController *)controller
WithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitle
tapBlock:(UIAlertCompletionBlock)tapBlock {
UIAlertController *alertController = [self alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
if(cancelButtonTitle != nil) {
UIAlertAction *cancelButton = [UIAlertAction
actionWithTitle:cancelButtonTitle
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
tapBlock(alertController, ALERTACTION_CANCEL); // CANCEL BUTTON CALL BACK ACTION
}];
[alertController addAction:cancelButton];
}
if(otherButtonTitle != nil) {
UIAlertAction *otherButton = [UIAlertAction
actionWithTitle:otherButtonTitle
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
tapBlock(alertController, ALERTACTION_OTHER); // OTHER BUTTON CALL BACK ACTION
}];
[alertController addAction:otherButton];
}
[controller presentViewController:alertController animated:YES completion:nil];
return alertController;
}
#end
in your ViewController.m
[UIAlertController showAlertIn:self WithTitle:#"" message:#"" cancelButtonTitle:#"Cancel" otherButtonTitles:#"Other" tapBlock:^(UIAlertController *alertController, NSInteger index){
if(index == ALERTACTION_CANCEL){
// CANCEL BUTTON ACTION
}else
if(index == ALERTACTION_OTHER){
// OTHER BUTTON ACTION
}
[alertController dismissViewControllerAnimated:YES completion:nil];
}];
NOTE: If you want to add more than two buttons then add another
more UIAlertAction to the UIAlertController.
Use UIAlertController instead of UIAlertView
-(void)showMessage:(NSString*)message withTitle:(NSString *)title
{
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
}];
[alert addAction:okAction];
UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[vc presentViewController:alert animated:YES completion:nil];
}
I tried the above methods, and no one can show the alert view, only when I put the presentViewController: method in a dispatch_async sentence:
dispatch_async(dispatch_get_main_queue(), ^ {
[self presentViewController:alert animated:YES completion:nil];
});
Refer to Alternative to UIAlertView for iOS 9?.
-(void)showAlert{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Title"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
[self showAlert]; // calling Method
Check this:
UIAlertController *alertctrl =[UIAlertController alertControllerWithTitle:#"choose Image" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *camera =[UIAlertAction actionWithTitle:#"camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self Action]; //call Action need to perform
}];
[alertctrl addAction:camera];
-(void)Action
{
}
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#"Are you sure you want to logout?"
message:#""
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:#"Logout"
style:UIAlertActionStyleDestructive
handler:^(UIAlertAction * action)
{
}];
UIAlertAction* noButton = [UIAlertAction
actionWithTitle:#"Cancel"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Handle no, thanks button
}];
[alert addAction:noButton];
[alert addAction:yesButton];
[self presentViewController:alert animated:YES completion:nil];
Is there a supported way of launching Google Authenticator on iOS?
I want to make it easier for customers to open the app and copy out the time-based code, before pasting it back into my app.
I've empirically discovered that this (Swift) code will launch the app:
UIApplication.sharedApplication().openURL(NSURL(string: "otpauth://")!)
...but I want to know if there is a better, supported way.
Specifically, is the otpauth:// protocol supported without arguments to simply launch the app?
Looking at the Git repo for the app it does seem like they have registered the Custom URL Schemes for bot otpauth and totp
https://github.com/google/google-authenticator/blob/bd50d15c348a978c314d2b30e586fbc562096223/mobile/ios/OTPAuth-Info.plist#L42
And here
https://github.com/google/google-authenticator/blob/bd50d15c348a978c314d2b30e586fbc562096223/mobile/ios/Classes/OTPAuthURL.h#L23
And here is the documentation on how exactly to build the url:
https://github.com/google/google-authenticator/wiki/Key-Uri-Format
After you form them correctly and get your app and the Google Authenticator app on the same device you would just need to test.
Objective C
if ([[[notification realRequestResults] valueForKey:#"action"] isEqualToString:#"2FA"]) {
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Two Factor Authentication"
message:#"Please, enter your Google Authenticator 2FA Token."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"Confirm Token"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
#try {
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
[userName text], #"loginName",
[passwordField text], #"password",
#"false", #"rememberMe",
[[alert textFields][0] text], #"tfa",
nil];
[self callWebserviceForIdentifier:AuthRequestInternalLogin
withParameters:parameters
onSuccessSelector:#selector(loginSuccessfulAgain:)
onFailureSelector:#selector(loginFailedAgain:)];
} #catch (NSException *exception) {
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"login"
message:[NSString stringWithFormat:#"%#", exception.description]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
} #finally {
}
}];
[alert addAction:defaultAction];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.delegate = self;
textField.placeholder = [NSMutableString stringWithString:#"Enter your 2FA token"];
textField.keyboardType = UIKeyboardTypeNumberPad;
textField.font = [UIFont systemFontOfSize:16.0];
textField.textAlignment = NSTextAlignmentCenter;
textField.textColor = UIColor.blackColor;
UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
[addButton setImage:[UIImage imageNamed:#"authenticator.png"] forState:UIControlStateNormal];
[addButton addTarget:self action:#selector(authenticatorBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
textField.rightViewMode = UITextFieldViewModeAlways;
textField.rightView = addButton;
}];
[self presentViewController:alert animated:YES completion:nil];
}
else {
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Warning"
message:#"Invalid Credentials. Please try again."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
[self stopAnimation];
}
}
-(IBAction)authenticatorBtnClicked:(id)sender{
NSString *AppStoreURL = #"https://apps.apple.com/in/app/google-authenticator/id388497605";
NSString *customAppURL = #"otpauth://";
BOOL canOpenURL = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customAppURL]];
NSString *url = canOpenURL ? customAppURL : AppStoreURL;
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:URL]];
}
In Info.plist File
I am facing few orientation issues in iOS 8 or later. If application is in background and in some other orientation, meanwhile some process of my application is finished, it gives an UIAlertView to user then my UIAlertView orientation is disturbed when it is in foreground.
I am using following code to lock alertView orientation.
-(void)didPresentAlertView:(UIAlertView *)alertView{
// UIAlertView in landscape mode
[UIView beginAnimations:#"" context:nil];
[UIView setAnimationDuration:0.1];
alertView.transform = CGAffineTransformRotate(alertView.transform, M_PI_2);
[UIView commitAnimations];
NSLog(#"didPresentCalled");
}
Please give me some suggestions. Thanks in advance.
UIAlertView is deprecated in iOS 8, so you will need to use UIAlertController instead.
NSString *title = #"Title";
NSString *message = #"Message";
NSString *buttonTitle = #"Dismiss";
if (NSClassFromString(#"UIAlertController") != Nil) // Yes, Nil
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:buttonTitle
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action) {
[self dismissViewControllerAnimated:YES completion:nil];
}]];
[self presentViewController:alert animated:YES completion:nil];
}
else
{
[[[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:buttonTitle
otherButtonTitles:nil] show];
}
Please see the link as I have answered this Question.
I have an UIAlertView which is getting shown perfectly in iOS 7 but in iOS 8, it does not show any buttons or labels. Alert is still visible but just a small white box.
The OK and cancel buttons take their events as well but no texts are visible.
I have used this alert to show on click of a button
- (IBAction)sel_btnLogout:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Logout!" message:#"Are you sure you want to logout?" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[alert show];
}
I checked the frame in iOS 8: it is giving (0,0,0,0) but in iOS 7 it is giving a definite value.
I also checked for iterating into the subviews of uialertview. In iOS7, it goes in the loop, as it finds alert's subviews. In iOS8, it says there are no subviews of alertView.
Check if the class is available
if ([UIAlertController class])
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Alert title" message:#"Alert message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
}
else
{
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:#"Alert title" message:#"Alert message" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
With iOS 8 you can set the title instead of the message:
[[[UIAlertView alloc] initWithTitle:#"AlertView in iOS 8." message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil]show];
UIAlertView is deprecated from iOS 8 for more information visit this
http://nshipster.com/uialertcontroller/.
https://developer.apple.com/LIBRARY/IOS/documentation/UIKit/Reference/UIAlertViewDelegate_Protocol/index.html
So if you're going to write separate code for iOS 7 and iOS 8, you should be using UIAlertController instead:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"AlertView in iOS 8" message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self dismissViewControllerAnimated:YES completion:nil];
}]];
[self presentViewController:alertController animated:YES completion:nil];
I got the answer to my issue. The issue was that I was using UIFont+Replacement category in my project. This was working fine on iOS 7 but on iOS 8 it was using few deprecated methods. Due to this, I don't know why, but only my alert view was not showing any labels.
Solution: Deleted the category from the project and set font through xib. Once we place the .tff file of any font in our project workspace, we see those font names in the xib under custom fonts. NO NEED TO USE UIFont+Replacement category.
Please read through the code below to understand how to add the fields and buttons to the alerts.
- (IBAction)UIAlertControllerWithActionSheetTextFields:(id)sender {
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:#"Info"
message:#"You are using UIAlertController with Actionsheet and text fields"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSLog(#"Resolving UIAlert Action for tapping OK Button");
[alert dismissViewControllerAnimated:YES completion:nil];
}];
UIAlertAction* cancel = [UIAlertAction
actionWithTitle:#"Cancel"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSLog(#"Resolving UIAlertActionController for tapping cancel button");
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:ok];
[alert addAction:cancel];
[alert addTextFieldWithConfigurationHandler:^(UITextField * textField) {
textField.accessibilityIdentifier = #"usernameTextField";
textField.placeholder = #"Enter your username";
textField.accessibilityLabel = #"usernameLabel";
}];
[alert addTextFieldWithConfigurationHandler:^(UITextField * textField) {
textField.placeholder = #"Enter your password";
textField.accessibilityIdentifier = #"paswordTextField";
textField.accessibilityLabel = #"passwordLabel";
}];
[self presentViewController:alert animated:YES completion:nil];
}
and if you need a project to completely refer the types of Alerts that are available in IOS, please follow my project from the below URL:
Alert variations in IOS
in iOS 8 you need to replace UIAletrview and UIActionSheet with UIAlertcontroller . You read first This documentation in apple forum
Apple Alertcontroller
You can check that code
if (([[[UIDevice currentDevice] systemVersion] compare:#"8.0" options:NSNumericSearch] == NSOrderedAscending))
{
// use UIAlertView
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:Title message:desc delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else {
// use UIAlertController
UIAlertController *alert = [UIAlertController alertControllerWithTitle:Title message:desc preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
}
let alert = UIAlertController(title: "Warning" as String , message: messageString as String, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.dismissViewControllerAnimated(true, completion: nil)
}
// Add the actions
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
i think this is not UIAlertview Issues.
please check this work fine..
i think your code issues...........
in any view controller put this code in viewDidLoad Like below:
- (void)viewDidLoad
{
[super viewDidLoad];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Title" message:#"My message" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[alert show];
}