UIAlertView And UIAlertController - ios

I am using SWIFT in xcode 6 to develope my application AND needs to support the APP for iphone 4 and later versions... So have selected the 'Deploment Target' as 7.1. In simple words needs to support iOS7, iOS8 AND iOS9...
When using Alert View I came across in many places discussing now we have to use newly introduced 'UIAlertController' rather than the old 'UIAlertView'...
By reading got to know UIAlertView is deprecated from ios 8.
But in my case as I have to support for ios 7.1 AND I can NOT only use 'UIAlertController'.
I started using as the following way as many tutorials explains...
if (objc_getClass("UIAlertController") != nil)
{
// Use UIAlertController
}
else
{
// Use UIAlertView
}
But in this way got to write the same code twice and really annoyiong... Either I have to create a custom Alertview combining both or needs to continue coding like this....
but just to test I've used only UIAlertView (ignoring UIAlertController) and the app runs fine even in ios 8 simulators... But the document says UIAlertView is deprecated from iOS 8.0...
So my question is, Like to hear what the best practice to continue my app with these API changes... Is it alright if I ignore 'UIAlertController' and work with old 'UIAlertView' until stop support for iOS7 one day... Will that effect in to my app in any way bad? Thanks

I've written a wrapper around these two classes which uses appropriate classes according to iOS version.
find it here
https://github.com/amosavian/ExtDownloader/blob/master/Utility%2BUI.swift
to show a simple alert use this:
Utility.UI.alertShow("message", withTitle: "title", viewController: self);
to show an action view: use this code:
let buttons = [Utility.UI.ActionButton(title: "Say Hello", buttonType: .Default, buttonHandler: { () -> Void in
print("Hello")
})]
Utility.UI.askAction("message", withTitle: "title", viewController: self, anchor: Utility.UI.AnchorView.BarButtonItem(button: uibarbuttontapped), buttons: buttons)
In case you are presenting action in iPhone, it will add a cancel button automatically. But you can have custom cancel button by defining a button with type of ".Cancel"
If you want show a modal alert view, use this code:
let cancelBtn = Utility.UI.AlertButton(title: "Cancel", buttonType: .Cancel, buttonHandler: nil)
let okBtn = Utility.UI.AlertButton(title: "OK", buttonType: .Default, buttonHandler: { (textInputs) -> Void in
print("OK button pressed")
})
Utility.UI.askAlert("message", withTitle: "title", viewController: self, buttons: [cancelBtn, okBtn], textFields: nil)
As you can see, the text fields is set to nil above. You can set it if you want ask something from user, like this:
let cancelBtn = Utility.UI.AlertButton(title: "Cancel", buttonType: .Cancel, buttonHandler: nil)
let okBtn = Utility.UI.AlertButton(title: "OK", buttonType: .Default, buttonHandler: { (textInputs) -> Void in
print("You entered" + textInputs[0])
}
})
let textFields = [Utility.UI.AlertTextField(placeHolder: "enter secret text here", defaultValue: "", textInputTraits: TextInputTraits.secretInput())]
Utility.UI.askAlert("Enter password", withTitle: "title", viewController: self, buttons: [cancelBtn, okBtn], textFields: textFields)
You can customize almost everything. e.g by defining custom textInputTrait you can customize text inputs easily. also you have not to deal with delegates, instead simple closures are there. Please read code to find out more.

Related

How to open the default mail app on iOS 14 without a compose view?

I want to open the default Mail application chosen by the user on iOS 14 - but without showing a compose view.
After signing up for an account, the user should confirm their email address, so I want to direct the user there.
There seem to be two known approaches based on the other questions I found:
UIApplication.shared.open(URL(string: "mailto://")!)
and
UIApplication.shared.open(URL(string: "message://")!)
The problem with the first option is that it will open an empty compose mail view in the app that comes up asking the user to type in a new email. That's not what I want. It would confuse users and they make think they have to send us an email. Putting in some text through parameters of the mailto URL syntax where I basically prepopulate the mail compose view with some text instructing to discard that new email draft and asking to check their email instead would work as a workaround but is not very nice.
The problem with the second option is that always opens the Mail.app, even if that is not the default mail app, and presumably it will ask the user to install the Mail.app if they deleted it from their phones because they have chosen e.g. Protonmail as their default mail app instead. Also not a very nice option for anyone who does not use Mail.app mainly.
So neither of the two approaches that have been proposed by other people solve my issue very nicely.
What is the best way to approach this?
Is there maybe some app to query iOS for the default mail app so at least I can try and launch that app if I know that app's custom URL scheme (e.g. googlegmail://)?
I ended up half-solving it by asking the user with an alert view about their preference, because I did not find a way to query iOS about it directly.
So first am showing an alert view like this:
func askUserForTheirPreference(in presentingViewController: UIViewController) {
let alertController = UIAlertController(title: nil, message: "pleaseConfirmWithApp", preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "Apple Mail", style: .default) { action in
self.open(presentingViewController, .applemail)
})
alertController.addAction(UIAlertAction(title: "Google Mail", style: .default) { action in
self.open(presentingViewController, .googlemail)
})
alertController.addAction(UIAlertAction(title: "Microsoft Outlook", style: .default) { action in
self.open(presentingViewController, .outlook)
})
alertController.addAction(UIAlertAction(title: "Protonmail", style: .default) { action in
self.open(presentingViewController, .protonmail)
})
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel) { action in
os_log("Cancelling", log: Self.log, type: .debug)
})
presentingViewController.present(alertController, animated: true)
}
Then, I am responding to the user's choice like this:
func open(_ presentingViewController: UIViewController, _ appType: AppType) {
switch appType {
case .applemail: UIApplication.shared.open(URL(string: "message:")!, completionHandler: { handleAppOpenCompletion(presentingViewController, $0) })
case .googlemail: UIApplication.shared.open(URL(string: "googlegmail:")!, completionHandler: { handleAppOpenCompletion(presentingViewController, $0) })
case .outlook: UIApplication.shared.open(URL(string: "ms-outlook:")!, completionHandler: { handleAppOpenCompletion(presentingViewController, $0) })
case .protonmail: UIApplication.shared.open(URL(string: "protonmail:")!, completionHandler: { handleAppOpenCompletion(presentingViewController, $0) })
}
}
private func handleAppOpenCompletion(_ presentingViewController: UIViewController, _ isSuccess: Bool) {
guard isSuccess else {
let alertController = UIAlertController(title: nil, message: "thisAppIsNotInstalled", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: .cancel))
presentingViewController.present(alertController, animated: true)
return
}
}
enum AppType {
case applemail, googlemail, outlook, protonmail
}
A clear limitation of this approach is of course that I am limiting the user to very specific apps (in this case Google Mail, iOS "default" Mail, Microsoft Outlook and ProtonMail).
So this approach does not really scale well.
But at least, you can cover a few favorite ones and go from there based on your users' feedback.
The main reason for jumping through these hoops of asking the first is that, at least at the moment, it seems impossible to get that information from iOS directly.
I also could not find a URL scheme that would always open the chosen default Mail app without showing the compose new email view.
I believe it can be done with a button with link: href=“message://“
Visual example from Revolut app:

Subsequent presentations of UIAlertController stutter

In a very loaded ViewController in an in-house app I've developed (iPad app written in Swift) for my company, I present alert style UIAlertControllers in a few circumstances. The first time an alert is presented, it always displays very smoothly. Any subsequent displays of an alert however end up being very stuttery, even for alerts that don't have much code surrounding their presentation and dismissal.
For example, if the user tries to dismiss the vc without saving after making changes (simple conditional of "if bool_Saved == false { create and display alert }") an alert is presented asking if they're sure they want to exit without saving. If they choose Yes, the vc is dismissed, otherwise, the alert is dismissed. The first creation and presentation of the alert animates smoothly, but anytime this conditional or any other code needs to present an alert, the presentation stutters its way through the animation.
The UI on this vc is pretty loaded. The whole screen is a scrollView with a contentView that contains 10 sub UIViews which in turn each have 3 UITextFields, ~9 UILabels, and ~8 UIButtons (the company wanted an exact digital replica of a paper form they've been using). Dismissing the vc and reloading it causes the next alert to again display smoothly, but again, subsequent alerts stutter through their present animation.
I've begun profiling in Instruments, but am a bit inexperienced in it and intend to use most of today getting more familiar with the various tools to hopefully find a source for this issue. What I'd like to know is if anyone has any suggestions on what might be causing this stuttering problem.
Thanks, and please let me know if there's any additional information I can provide.
Editing with code snippet described above:
func cancelTapped() {
if savedOnce == false {
let alert_Exit = UIAlertController(title: "Exit Inspection?", message: "Unsaved changes to the sheet will be lost upon exit. Are you sure you want to exit without saving?", preferredStyle: .alert)
let action_No = UIAlertAction(title: "No", style: .cancel, handler: nil )
let action_Yes = UIAlertAction(title: "Yes", style: .default, handler: { [unowned self]
(action) in
self.exitSheet()
})
alert_Exit.addAction(action_No)
alert_Exit.addAction(action_Yes)
present(alert_Exit, animated: true, completion: nil)
} else {
exitSheet()
}
}
You are not dismissing the alert. Insert that line in your Yes button.
let action_Yes = UIAlertAction(title: "Yes", style: .default, handler: { [unowned self]
(action) in
alert_Exit.dismiss(animated: true)
self.exitSheet()
})
When you create the alert a second time, it probably results in a conflict with previous alert hidden somewhere in your view that wasn't dismissed. How loaded the VC is, it probably doesn't make any difference.
Style .cancel will remove itself anyway, whilst .default will require you to remove the alert.

UIAlertController foreground is dimmed when it should not be

I have a strange issue which is affecting all of many UIAlertControllers shown throughout my app - the AlertControllers' white foreground appears dimmed, or less bright, than it should be.
The easiest way to describe it is to illustrate the desired and expected effect I obtain by placing the relevant code in a fresh 'Test' Single View application (Swift 3 - I should note that the actual app is a Single View application using Swift 2.3).
In my 'Test' app, the code below uses a deprecated AlertView to show a sample message, then builds a AlertController and shows that immediately 'after'. There is no need to use the AlertView except to highlight the contrast in foreground 'white' - the problematic behaviour is the same if I comment out the AlertView.
Problematic behaviour:
Image 1: Test app: the AlertView is shown and the AlertController then shows behind it. Note the whiteness/brightness of the AlertView foreground.
Image 2: Test app: when the AlertView is dismissed, the AlertController is then the uppermost viewcontroller and as expected and desired, its foreground brightness is exactly the same as the AlertView's previously was
Image 3: real app: same code, also positioned in viewDidAppear - the AlertView is shown with the expected whiteness/brightness
Image 4: real app: when the AlertView is dismissed, the AlertController is then uppermost, but its foreground is nowhere near as bright / white as the AlertView's was, OR as it was in the Test app example, image 2.
As previously stated, the behaviour is the same even if I eliminate the AlertView step (which is just for contrast).
One further observation - often when I observe the behaviour, just momentarily when an affected AlertController first appears, as in for maybe 1/4 or 1/8 of a second, its foreground is the correct whiteness/brightness, but then an instant later it becomes dimmed, per the stated problem.
One other observation - some AlertControllers in the real app display properly with the correct level of brightness, but many others do not.
One last observation - I have user the 'View UI Hierarchy' in Xcode and there does not appear to be anything 'on top of' the affected AlertController.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
UIAlertView(title: "My AlertView Title", message: "My AlertView Message", delegate: self, cancelButtonTitle: "OK").show()
let alertTitle = "My AlertController Title"
let msg = "\r\r\r\r\r\r\r\rMy AlertController Msg"
let alertController = UIAlertController(title: alertTitle, message: msg, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Don't show this again", style: .cancel) { (action:UIAlertAction!) in
print("Dismiss button pressed")
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "Action 1", style: .default) { (action:UIAlertAction!) in
print("I'm action1!!")
}
alertController.addAction(OKAction)
let OK2Action = UIAlertAction(title: "Action2", style: .default) { (action:UIAlertAction!) in
print("I'm action2")
}
alertController.addAction(OK2Action)
present(alertController, animated: false, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Any help as to this puzzle gratefully received, thanks!
EDIT:
thanks to #Richard G for putting me on the right track - I still have the problem but with more clarity.
So, it you look at the two screenshots below side by side, they are both from the real app, both use the code shown above to generate the UIAlertController (I have now delete the UIAlertView line as it isn't needed), the only difference between the one on the left and one on the right is the one on the right has these 3 lines of code added:
let backView = alertController.view.subviews.last?.subviews.last
backView?.layer.cornerRadius = 10.0
backView?.backgroundColor = UIColor.whiteColor()
side by side UIAlertControllers 1 transparent 1 not
According to Apple, "The UIAlert​Controller 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." OK, so this is hacking into it, and it proves that somehow the alertController has acquired, prior to displaying it, a backgroundColor which was partly transparent.
By setting the backgroundColor to UIColor.whiteColor() the problem is fixed, but the solution should be unnecessary - how on earth did the problem arise in the first place?
How was the backgroundColor somehow set to have a transparency when Apple doesn't even expose that property to me to be able to set?
any answers gratefully received!
After seeing an image that you have uploaded I can mention some point.
The UIAlertController is little bit transparent if you notice.
Since UIAlertController is transparent so the background will affect on appearance of alert controller.
NOTE: In case 1 & 2 background is white and case 3 & 4 background is black.
So what you can do it make background as bright as in case 1 and case 2 (from image).
**EDIT : **
TO change background color of UIAlertController you can do like...
let subView = alertController.view.subviews.first!;
var alertContentView = subView.subviews.first!;
alertContentView.backgroundColor = UIColor.darkGray;
alertContentView.layer.cornerRadius = 5;
UIAlertView and UIAlertController has same background color and alpha value.
But in your case AlertView is displayed above AlertController, ie why it feels like UIAlertView is Whitier than UIAlertController.

In Swift how to create Custom Alert View [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have to implement a Custom alerts in my App programmatically using Swift language. i tried implementing using some third party library "SCLAlertView" but not able to understand from that, i need a implement simple alert pop ups with dynamic message and number of button changes in App. As there were lots of AlertView in my App. so i need to update the dynamically.
below i have attached an sample image of custom alert how it looks to implement
Please help me to implement this feature.
After the installing pod with pod SCLAlertView
You can choose Alert view Style and Alert View Animation style with these enums
enum SCLAlertViewStyle: Int {
case Success, Error, Notice, Warning, Info, Edit, Wait
}
public enum SCLAnimationStyle {
case NoAnimation, TopToBottom, BottomToTop, LeftToRight, RightToLeft
}
SCLAlertView has many Control groups like add textField , buttons and icons
here is a adding button function codes
let alertView = SCLAlertView()
alertView.addButton("First Button", target:self, selector:Selector("firstButton"))
alertView.addButton("Second Button") {
println("Second button tapped")
}
alertView.showSuccess("Button View", subTitle: "This alert view has buttons")
and Alert view custom types
SCLAlertView().showError("Hello Error", subTitle: "This is a more descriptive error text.") // Error
SCLAlertView().showNotice("Hello Notice", subTitle: "This is a more descriptive notice text.") // Notice
SCLAlertView().showWarning("Hello Warning", subTitle: "This is a more descriptive warning text.") // Warning
SCLAlertView().showInfo("Hello Info", subTitle: "This is a more descriptive info text.") // Info
SCLAlertView().showEdit("Hello Edit", subTitle: "This is a more descriptive info text.") // Edit
in Github Page you will find many beatiful desing alert views , it is easy to use
https://github.com/vikmeup/SCLAlertView-Swift
Just add different UIAlertAction to your UIAlertController whenever you want it to.
let alertAction: UIAlertAction = UIAlertAction(title: "YES", style: UIAlertActionStyle.Default, handler: {
//Code goes here
})
let alertAction2: UIAlertAction = UIAlertAction(title: "NO", style: UIAlertActionStyle.Default, handler: {
//Code goes here
})
let alertAction3: UIAlertAction = UIAlertAction(title: "Maybe", style: UIAlertActionStyle.Default, handler: {
//Code goes here
})
alert.addAction(alertAction)
alert.addAction(alertAction2)
alert.addAction(alertAction3)
You can dynamically add UIAlertAction's to your UIAlertController depending on your needs. If you only need two buttons, then don't add alertAction3. If you need three or four, then add them as necessary.

Do I have to hard-code / localise myself the "OK" button when generating an alert in swift?

I have a convenience method in Swift (iOS 8+) for displaying an error message. So far it looks like this:
// Supplied with a category code and an error code, generates an error dialogue box.
// Codes rather than strings because this needs to be localisable.
func showErrorDialogue(categoryCode: String, _ errorCode: String) -> () {
// Fetch the actual strings from the localisation database.
let localisedCategory = NSLocalizedString(categoryCode, comment: categoryCode)
let localisedError = NSLocalizedString(errorCode, comment: errorCode)
// Create an alert box
let alertController = UIAlertController(
title: localisedCategory,
message: localisedError,
preferredStyle: .Alert
)
alertController.addAction(
UIAlertAction(
title: "OK", // FIXME: why isn't this localised?
style: .Default,
handler: { (action) in return }
)
)
self.presentViewController(alertController, animated: true) { return }
}
It seems odd that I can't just say "I'm only adding one button to this alert box, so please assume it's going to be the locale-default OK button". The best solution I've found so far with limited Googling appears to be Steal them from the System and hope which is more than a little dodgy.
As far as I know, there are no better ways to do this than stealing it from the system like you found.
Though it's not the hardest thing to localize, I agree it would be great if Apple made that automatic in a future version of the OS.

Resources