Swift: Show UIAlertController in didReceiveLocalNotification method - swift2

I want to show alert when notification is fired while app is running, here is tutorial which i used for local notifications. In tutorial, it uses UIAlertView to show alert and it works, here is code:
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
// Point for handling the local notification when the app is open.
// Showing reminder details in an alertview
UIAlertView(title: notification.alertTitle, message: notification.alertBody, delegate: nil, cancelButtonTitle: "OK").show()
}
but it gives warning that UIAlertView is deprecated in iOS 9, so i used UIAlertController, but when i run it it gives warning:
Attempt to present <UIAlertController: 0x7c322a00> on <xxx> whose view is not in the window hierarchy!
Here is my didReceiveLocalNotification method:
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
let alert = UIAlertController(title: "", message: notification.alertBody, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in
}))
self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
}
How i can show UIAlertController in didReceiveLocalNotification method? I also tried:
let activeViewCont = application.windows[0].rootViewController?.presentedViewController
activeViewCont!.presentViewController(alert, animated: true, completion: nil)

Try this:
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
var topController : UIViewController = (application.keyWindow?.rootViewController)!
while ((topController.presentedViewController) != nil) {
topController = topController.presentedViewController!
}
let alert = UIAlertController(title: "", message: notification.alertBody, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in}))
topController.presentViewController(alert, animated: true, completion: nil)
})
Hope it helps.

Related

Creating an Image in UIAlertController

can anyone please tell me a way of adding in an image into a UIAlertController? This is the code I have generated to produce the Alert Controller.
I believe I need to add a subview but not sure?
let myAlert = UIAlertController(title: "Congratualtions", message: "Correct answer selected, move on to next level", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default)
{
action in self.dismiss(animated: true, completion: nil)
}
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion:nil)
The code works but i do not know how add an image into the action sheet...
You can use this library (MZFormSheetPresentationController) to create the AlertViews with Images,Buttons and lots of functions. You can design viewController as you want...
func formSheetControllerWithNavigationController() -> UINavigationController {
return self.storyboard!.instantiateViewController(withIdentifier: "formSheetController") as! UINavigationController
}
func passDataToViewControllerAction() {
let navigationController = self.formSheetControllerWithNavigationController()
let formSheetController = MZFormSheetPresentationViewController(contentViewController: navigationController)
formSheetController.presentationController?.isTransparentTouchEnabled = false
formSheetController.presentationController?.shouldCenterVertically = true
formSheetController.presentationController?.shouldCenterHorizontally = true
formSheetController.presentationController?.shouldDismissOnBackgroundViewTap = true
let yourViewController = navigationController.viewControllers.first as! EventDisplayViewController
yourViewController.delegate = self
self.present(formSheetController, animated: true, completion: nil)
}

Trying to pass data between two view controllers after login

What I am trying to do here is once login is successful, go to the "HomeLoginViewController" which is a navigation controller with its root controller being "HomepageViewController" but I also need to send the surname of the user that logged in to a label in the "HomepageViewController".
If I put the "self.presentViewController(controller, animated: true, completion: nil)" first then this goes to the "HomepageViewController" and sends the surname but does not display the navigation bar.
If I put the "self.presentViewController(alert, animated: true, completion: nil)" first it displays the navigation bar but does not send the surname. I cannot fix this code to do both :( Please help.
class LoginViewController: UIViewController {
let ref = Firebase(url: "https://<myfirebase>.firebaseio.com/")
#IBOutlet weak var forenamefield: UITextField!
#IBOutlet weak var surnamefield: UITextField!
#IBOutlet weak var emailfield: UITextField!
#IBOutlet weak var passwordfield: UITextField!
#IBOutlet weak var loginbutton: UIButton!
#IBAction func signinaction(sender: AnyObject) {
let user = self.forenamefield.text!
let usersurname = self.surnamefield.text!
ref.authUser(emailfield.text, password: passwordfield.text, withCompletionBlock: { error, authData in
if error != nil
{
let alert = UIAlertController(title: "Error", message: "Incorrect Email and Room Number.", preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
print("Can Not Sign In")
}
else
{
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let viewName:NSString = "HomeView"
let vc = storyboard.instantiateViewControllerWithIdentifier(viewName as String) as! HomeLoginViewController
let controller = storyboard.instantiateViewControllerWithIdentifier("ViewHome") as! HomepageViewController
controller.labelText = self.surnamefield.text!
let uid = authData.uid
print("Success with user: \(uid)")
let alert = UIAlertController(title: "Success", message: "Welcome \(user) \(usersurname)", preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: "Ok", style: .Default) { _ in
self.navigationController?.presentViewController(vc, animated: true, completion: nil)
}
alert.addAction(action)
self.presentViewController(controller, animated: true, completion: nil)
self.presentViewController(alert, animated: true, completion: nil)
}
})
}
You can try use NSUserDefaults when login details are correct
// In login screen before go to home, save the username as key "userID"
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(username, forKey: "userID")
defaults.synchronize()
// In your home, viewDidLoad() retrieve it back
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
let userID = (defaults.objectForKey("userID") as? String)!

Unable to dismissViewControllerAnimated iOS 9.3

I am showing an UIAlertController and in UIAlertAction I am dismissing view controller. It was working fine prior to iOS 9.3. But in iOS 9.3 it is not working. Following is the code.
let alertController = UIAlertController(title: "Logged In Successfully", message: "asda", preferredStyle: .Alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { UIAlertAction in
self.dismissViewControllerAnimated(true, completion: nil)
}
// Add the actions
alertController.addAction(okAction)
// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)
Try to put breakpoint in the dismissViewControllerAnimated line, and check if it's getting there when you press OK.
If it's not - try to replace
UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { UIAlertAction in
self.dismissViewControllerAnimated(true, completion: nil)
}
with this:
UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { _ in
self.dismissViewControllerAnimated(true, completion: nil)
}

UIAlertController Segue to Different Page (Swift)

I was able to write a UIAlertController for my button, and it work fine, but I don't know how to segue to a different page once I press the YES or OK button. At the moment, the YES or OK button goes nowhere.
#IBAction func SubmitButton(sender: AnyObject) {
if a > 28.87 {
var alert = UIAlertController(title: "H4 with Guide Pins", message: "Can it be removed?", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "YES", style: UIAlertActionStyle.Default, handler: nil))
alert.addAction(UIAlertAction(title: "NO", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
else if data2.text == "" {
var alert = UIAlertController(title: "Dimension", message: "Missing Data Input.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
else {
var alert = UIAlertController(title: "H4 with Guide Pins", message: "Enter Swallow Dimension.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
self.view.endEditing(true)
}
}
You could create a segue in your storyboard, control dragging from the yellow view controller at the top of a scene to a new view controller. Then give that segue an identifier in the inspector. You can call that from the handler in your code.
alert.addAction(UIAlertAction(title:"OK", style: .Default, handler: { action in self.performSegueWithIdentifier("mySegueIdentifier", sender: self) }
Solution in Swift 3
let alertController = UIAlertController(title: "Email Verification Required", message: "You will receive an email shortly to verify your account this must be done before you can sign in", preferredStyle: .alert)
let backToSignIn = UIAlertAction(title: "OK", style: .cancel, handler: { action in self.performSegue(withIdentifier: "backToSignIn", sender: self)})
alertController.addAction(backToSignIn)
self.present(alertController, animated: true, completion: nil)
Where backToSignIn is the segue name.

Add image into UIAlertController in swift

I want to have a simple UIAlertController with image in it. what should I do?
let alertMessage = UIAlertController(title: "Service Unavailable", message: "Please retry later", preferredStyle: .Alert)
alertMessage.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alertMessage, animated: true, completion: nil)
Try this:
let alertMessage = UIAlertController(title: "Service Unavailable", message: "Please retry later", preferredStyle: .Alert)
let image = UIImage(named: "myImage")
var action = UIAlertAction(title: "OK", style: .Default, handler: nil)
action.setValue(image, forKey: "image")
alertMessage .addAction(action)
self.presentViewController(alertMessage, animated: true, completion: nil)
a snippet of code that works for me:
func alert2 (heading: String,image: String){
if self.presentedViewController == nil {
let alertController = UIAlertController(title: nil, message: " ", preferredStyle: .Alert )
var imageView = UIImageView(frame: CGRectMake(10, 6, 300, 50))
imageView.image = UIImage(named: display.0)
alertController.view.addSubview(imageView)
alertController.addAction(UIAlertAction(title: "Maps", style: UIAlertActionStyle.Default, handler: {(action:UIAlertAction!) in self.makeContact("maps")}))
this is my code to image in alert view
var logoAlert = UIImageView(frame: CGRectMake(0, 0, 300, 250))
logoAlert.image = UIImage(named: "v1.png")
infoController.view.addSubview(logoAlert)
NSLog("image is draw")
logoalert is dtring
infoController - is name of fun
rename it, and all will be alright
paste this code in fun of alert controller

Resources