Im currently using a custom tabBarController to navigate to my apps. I'm using storyboard for some of the view controllers and others Im not. the problem is that the viewControllers that are not in story are not being re instantiate. When I navigate to the view the first time everything work fine. If I exit and then come back the same view does not refresh. the same data is re-added on top of the old data. this happen to the views I could not add using an identifier to. The one i did self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController work fine. How can I solve this. Thank you in advance.
this work fine: this view behave normally because it was instantiate
let dashboardController = self.storyboard?.instantiateViewController(withIdentifier: "DashboardViewController") as! DashboardViewController
let dashboardTabImg = UIImage.fontAwesomeIconWithName(.User, textColor: iconColor, size: iconSize )
let dashboardTabImgSelected = UIImage.fontAwesomeIconWithName(.User, textColor: iconColor, size: iconSize)
dashboardController.tabBarItem = UITabBarItem(title: "Login", image: dashboardTabImg, selectedImage: dashboardTabImgSelected )
// this does not work properly because it was not instantiate.
//receivePostRequest VC
let receivePostRequest = UINavigationController(rootViewController: ReceivePostRequestViewController())
let receivePostRequestImg = UIImage.fontAwesomeIconWithName(.Dollar, textColor: iconColor, size: iconSize )
let receivePostRequestImgSelected = UIImage.fontAwesomeIconWithName(.Dollar, textColor: iconColor, size: iconSize)
receivePostRequest.tabBarItem = UITabBarItem(title: "Request", image: receivePostRequestImg, selectedImage: receivePostRequestImgSelected )
//This is the viewController that is im having issues with
import UIKit
import Firebase
class ReceivePostRequestViewController: UIViewController {
let receiveRequestSwitch = UISwitch()
let receiveRequestLabel = UILabel()
override func viewWillAppear(_ animated: Bool) {
navigationItem.title = "Post Request"
receiveRequestSwitch.isOn = false
checkFirBaseForSwitchStatus()
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
pageSetup()
receiveRequestSwitch.addTarget(self, action: #selector(postRequestSwitchButtonPressed), for: .touchUpInside)
}
}
enum receivePostStatusEnums{
case pending
case accepted
case disabled
case declined
case contactCustomerSupport
case error
}
extension ReceivePostRequestViewController {
func pageSetup(){
receiveRequestLabel.text = "Receive Post Request"
receiveRequestLabel.isUserInteractionEnabled = true
receiveRequestLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(receiveRequestLabel)
receiveRequestLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 80).isActive = true
receiveRequestLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 26).isActive = true
receiveRequestLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -26).isActive = true
receiveRequestLabel.heightAnchor.constraint(equalToConstant: 44).isActive = true
receiveRequestLabel.addSubview(receiveRequestSwitch)
receiveRequestSwitch.frame = CGRect(x: 0, y: 0, width: 40, height: 44)
receiveRequestSwitch.translatesAutoresizingMaskIntoConstraints = false
// receiveRequestSwitch.leftAnchor.constraint(equalTo: receiveRequestLabel.leftAnchor).isActive = true
receiveRequestSwitch.rightAnchor.constraint(equalTo: receiveRequestLabel.rightAnchor).isActive = true
receiveRequestSwitch.centerYAnchor.constraint(equalTo: receiveRequestLabel.centerYAnchor).isActive = true
}
func checkFirBaseForSwitchStatus(){
FIRDatabase().childRef(refUrl: "frontEnd/users/\((FIRAuth.auth()?.currentUser?.uid)!)/receivePostRequest/info").observe(.value, with: {snapshot in
if let dict = snapshot.value as? NSDictionary {
if let stat = dict["isAvailabileForRequest"] as? Bool {
if stat{
self.receiveRequestSwitch.isOn = true
}else{
self.receiveRequestSwitch.isOn = false
}
}
}else{
self.receiveRequestSwitch.isOn = false
}
})
}
func postRequestSwitchButtonPressed(){
if self.receiveRequestSwitch.isOn{
receiveRequestSwitch.isOn = false
let userId = FIRAuth.auth()?.currentUser?.uid
FIRDatabase.database().reference().child("frontEnd/users/\(userId!)/receivePostRequest/application").observeSingleEvent(of: .value, with: {snapshot in
if let dict = snapshot.value as? [String:AnyObject]{
if let status = dict["status"] as? String {
print(status)
switch status {
case "pending":
print("its pending")
self.simpleAlert(title: nil, message: "Your application is currently Being Reviewed, no action is required from you")
case "accepted":
print("its accepted")
let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PostSelectViewController")
self.present(viewController, animated: true, completion: nil)
case "disabled":
print("its disabled")
self.simpleAlert(title: nil, message: "Your account is currently disabled if you have any questions please contact customer service")
case "declined":
self.simpleAlert(title: nil, message: "After reviewing your application we will not be able to continue your application we are very sorry. If you feel this was an error please contact our customer service")
case "contactCustomerSupport":
print("its contactCustomerSupport")
self.simpleAlert(title: nil, message: "Please contact customer")
case "error":
print("its error")
self.simpleAlert(title: nil, message: "We can not process your request please try again at a later time")
default:
print ("error")
self.simpleAlert(title: nil, message: "We can not process your request please try again at a later time")
}
}
return
}
//user need submit application here
print("user need to fill out application page")
let applicationNavController = UINavigationController(rootViewController:ReceivePostRequestApplicationViewController())
self.present(applicationNavController, animated: true, completion: nil)
})
}else{
//update info to turn switch off
FIRDatabase().childRef(refUrl: "frontEnd/users/\((FIRAuth.auth()?.currentUser?.uid)!)/receivePostRequest/info").updateChildValues(["isAvailabileForRequest":false], withCompletionBlock: { (error, fir) in
if error != nil {
print(error?.localizedDescription)
return
}
let ac = UIAlertController(title: nil, message: "You will no longer receive service request", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: { (okAction) in
self.dismiss(animated: true, completion: nil)
})
ac.addAction(okAction)
self.present(ac, animated: true, completion: nil
)
})
}
}
}
Related
I have a UITabBarController as rootviewcontroller with 4 tabs and sign in with a Apple button that sign you in and present the UITabBarController. However when I sign in with Apple only...data only load on the first tab.. and all other tabs are blank like a regular storyboard...other sign in with google and Facebook loads all tabs data except Apple sign in ?? I can’t fire out why.. I present every storyboard with modalPresentingStyle= .fullScreen.
import UIKit
import AuthenticationServices
class LoginVC: UIViewController, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
#IBOutlet weak var appleBtn: Button!
var userEmail: String?
var savedUserID: String?
override func viewDidLoad() {
super.viewDidLoad()
appleBtn.addTarget(self, action: #selector(handleAppleIdRequest), for: .touchUpInside)
performExistingAccountSetupFlows()
// Do any additional setup after loading the view.
}
#objc func handleAppleIdRequest() {
let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]
let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = self
authorizationController.performRequests()
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
// Create an account in your system.
// For the purpose of this demo app, store the these details in the keychain.
KeychainItem.currentUserIdentifier = appleIDCredential.user
KeychainItem.currentUserFirstName = appleIDCredential.fullName?.givenName
KeychainItem.currentUserLastName = appleIDCredential.fullName?.familyName
KeychainItem.currentUserEmail = appleIDCredential.email
print("User Id - \(appleIDCredential.user)")
print("User Name - \(appleIDCredential.fullName?.description ?? "N/A")")
print("User Email - \(appleIDCredential.email ?? "N/A")")
print("Real User Status - \(appleIDCredential.realUserStatus.rawValue)")
if let identityTokenData = appleIDCredential.identityToken,
let identityTokenString = String(data: identityTokenData, encoding: .utf8) {
print("Identity Token \(identityTokenString)")
}
//Show Home View Controller
guard let tabBar = self.storyboard?.instantiateViewController(withIdentifier: "tabBar") as? UITabBarController else { return }
self.present(tabBar, animated: true, completion: nil)
} else if let passwordCredential = authorization.credential as? ASPasswordCredential {
// Sign in using an existing iCloud Keychain credential.
let username = passwordCredential.user
let password = passwordCredential.password
// For the purpose of this demo app, show the password credential as an alert.
DispatchQueue.main.async {
let message = "The app has received your selected credential from the keychain. \n\n Username: \(username)\n Password: \(password)"
let alertController = UIAlertController(title: "Keychain Credential Received",
message: message,
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
}
func performExistingAccountSetupFlows() {
// Prepare requests for both Apple ID and password providers.
let requests = [ASAuthorizationAppleIDProvider().createRequest(),
ASAuthorizationPasswordProvider().createRequest()]
// Create an authorization controller with the given requests.
let authorizationController = ASAuthorizationController(authorizationRequests: requests)
authorizationController.delegate = self
authorizationController.presentationContextProvider = self
authorizationController.performRequests()
}
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return self.view.window!
}
#IBAction func otherSignUP(_ sender: Any) {
guard let otherLogin = self.storyboard?.instantiateViewController(identifier: "otherLogin") as? OtherLoginVC else {return}
otherLogin.modalPresentationStyle = .fullScreen
self.present(otherLogin, animated: true, completion: nil)
}
}
I want to show this popup in my view controller and when I push the button go back
This is the part of I want to show the pop up:
#IBAction func entrarAction(_ sender: UIButton) {
sender.isEnabled = false
let l = showLoader()
let user = userTextField.text!
let passwd = passwordTextField.text!
if !validaEntrada(user: user, password: passwd){
// TODO: show errors!
// Show popup here
return
}
let login = VenLogin(usuario: user, contrasenia: passwd)
try! RequestManager.fcReq(url: .login, req: login, res: VenLoginResponse.self) { loginResp, err in
sender.isEnabled = true
l.dismiss(animated: true, completion: {
if let r:VenLoginResponse = loginResp as? VenLoginResponse {
if r.code0 {
let c = self.getAppDelegateContainer()
c.register(from: .loginResponse, value: r)
c.register(from: .tokenJwt, value: r.tokenJwt!)
self.pushServicios()
}
}
})
}
}
Instead of a custom View Controller for your popup you can use an Alert View
#IBAction func entrarAction(_ sender: UIButton) {
sender.isEnabled = false
let l = showLoader()
let user = userTextField.text!
let passwd = passwordTextField.text!
if !validaEntrada(user: user, password: passwd){
// Show popup here
showErrorAlert()
return
// the rest of your code
}
func showErrorAlert() {
let alert = UIAlertController(title: "Usuario o contraseña no válido", message: "", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Aceptar", style: UIAlertAction.Style.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
But if you still want to use your custom View Controller use this to show the popup:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let popupErrorLogin = storyboard.instantiateViewController(withIdentifier: "PopupErrorLogin") as! PopupErrorLogin
self.present(popupErrorLogin, animated: true, completion: nil)
And this to close it:
#IBAction func aceptarAction(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
I have a ViewController called Home, in Home viewDidAppear have a function CheckStatus that I need to call every time it received a specific notify.
So currently in AppDelegate, I call this code to present Home anytime the notify is received, which cause memory leaking and crashes:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "MainTabBarController") as! MainTabBarController
//Home is the first ViewController of the TabBar
self.window?.rootViewController = controller
What is the solution for this?
Updated ViewDidAppear and it's functions
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.tabBarController?.tabBar.isHidden = false
setupTabbar() //setup tab bar UI
self.locationService.getLocation()
self.checkRequestStatus()
self.navigationController?.setNavigationBarHidden(false, animated: animated)
}
func checkRequestStatus(){
API.checkRequestStatus{ [weak self] json, error in
if let error = error {
}else {
if let json = json {
let status = json[Const.STATUS_CODE].boolValue
if (!API.isSuccess(response: json)){
if (API.getErrorCode(response: json) == Const.INVALID_TOKEN){
let alert = UIAlertController(title: "Message".localized(), message: "You have logged in from another device. Please login again.", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler:
{(action:UIAlertAction!) in
let defaults = UserDefaults.standard
print ("got here")
defaults.set("", forKey: Const.Params.TOKEN)
if self?.presentingViewController != nil {
self?.dismiss(animated: false, completion: {
self?.navigationController!.popToRootViewController(animated: true)
})
}
else {
self?.navigationController!.popToRootViewController(animated: true)
}
}))
self!.present(alert, animated: true, completion: nil)
}
}
let defaults = UserDefaults.standard
if let currency : String = json[Const.CURRENCEY].rawString() {
defaults.set(currency, forKey: json[Const.CURRENCEY].rawString()!)
}
if let cancellation : Int = json[Const.CANCELLATION_FINE].intValue {
let str : String = String(cancellation)
defaults.set(str, forKey: Const.CANCELLATION_FINE)
}
if(status){
let requestDetail: RequestDetail = RequestDetail()
let jsonAry:[JSON] = json[Const.DATA].arrayValue
let defaults = UserDefaults.standard
if jsonAry.count > 0 {
let driverData = jsonAry[0]
if driverData.exists() {
defaults.set(driverData["request_id"].stringValue, forKey: Const.Params.REQUEST_ID)
defaults.set(driverData["provider_id"].stringValue, forKey: Const.Params.DRIVER_ID)
requestDetail.initDriver(rqObj: driverData)
}
let invoiceAry:[JSON] = json[Const.INVOICE].arrayValue
if invoiceAry.count > 0 {
let invoiceData = invoiceAry[0]
defaults.set(invoiceData.rawString(), forKey: Const.CURRENT_INVOICE_DATA)
requestDetail.initInvoice(rqObj: invoiceData)
}
self?.processStatus(json: json, tripStatus:requestDetail.tripStatus)
} else {
requestDetail.tripStatus = Const.NO_REQUEST
let defaults = UserDefaults.standard
defaults.set(Const.NO_REQUEST, forKey: Const.Params.REQUEST_ID)
}
}
}
}
}
}
You are force-unwrapping self:
self!.present(alert, animated: true, completion: nil) First see if your app still crashes when your replace the call with self?..
I am trying to create an app that requires the user to successfully enter a pin before being allowed onto the rest of the app.
I did some searching around and found a basic existing coredata example app that works here.
I went into the xcdatamodel and deleted their attributes and replaced with "pin" which is a String. Here is a screenshot of the xcdatamodel.
Then I modified the ViewController so that the createData UIbutton opens a alertController that prompts the user to enter a new pin twice, checks they are the same, and if they are it creates a coredata entry with that pin.
Here is the relevant code of the ViewController:
import UIKit
import CoreData
class ViewController: UIViewController {
var firstPinNumber:String = ""
var secondPinNumber:String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func createData(_ sender: Any) {
let enterPinAlertController = UIAlertController(title: "Enter New PIN", message: "", preferredStyle: .alert)
enterPinAlertController.addTextField{ (textField1:UITextField)->Void in
textField1.placeholder = "Enter PIN"
textField1.isSecureTextEntry = true
}
enterPinAlertController.addTextField{ (textField2:UITextField)->Void in
textField2.placeholder = "Re-Enter PIN"
textField2.isSecureTextEntry = true
}
let okAction = UIAlertAction(title: "OK", style: .cancel) {(action) in
if let textFields = enterPinAlertController.textFields {
let theTextFields = textFields as [UITextField]
self.firstPinNumber = theTextFields[0].text!
self.secondPinNumber = theTextFields[1].text!
if self.firstPinNumber != self.secondPinNumber {
print ("PINs dont match!")
let pinsDontMatchAlertController = UIAlertController(title: "PINs don't match!", message: "Try again", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel) {(action) in
}
pinsDontMatchAlertController.addAction(okAction)
self.present(pinsDontMatchAlertController, animated: true, completion: nil)
}
}
}
enterPinAlertController.addAction(okAction)
self.present(enterPinAlertController, animated: true, completion: nil)
createPIN(pinNum: secondPinNumber)
}
func createPIN(pinNum: String){
//As we know that container is set up in the AppDelegates so we need to refer that container.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
//We need to create a context from this container
let managedContext = appDelegate.persistentContainer.viewContext
//Now let’s create an entity and new user records.
let userEntity = NSEntityDescription.entity(forEntityName: "User", in: managedContext)!
let user = NSManagedObject(entity: userEntity, insertInto: managedContext)
user.setValue(pinNum, forKeyPath: "pin")
print(user.value(forKey: "pin") as Any)
//Now we have set the pin. The next step is to save it inside the Core Data
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
#IBAction func retrieveData(_ sender: Any) {
let storedPin = retrievePIN()
print(storedPin)
}
func retrievePIN()->String {
var storedPin:String = ""
//As we know that container is set up in the AppDelegates so we need to refer that container.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return "" }
//We need to create a context from this container
let managedContext = appDelegate.persistentContainer.viewContext
//Prepare the request of type NSFetchRequest for the entity
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
fetchRequest.fetchLimit = 1
// fetchRequest.predicate = NSPredicate(format: "username = %#", "Ankur")
// fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "email", ascending: false)]
//
do {
let result = try managedContext.fetch(fetchRequest)
for data in result as! [NSManagedObject] {
if data.value(forKey: "pin") != nil {
storedPin = data.value(forKey: "pin") as! String
print(storedPin)
} else {
print ("Found nil")
}
}
} catch {
print("Failed")
}
return storedPin
}
Using breakpoints I have ascertained that it enters the createPin() function, but it seems to enter that function BEFORE it presents the enterPinAlertController to enter the new pin, even though createPin() is called AFTER the enterPinAlertController is presented.
Also if I use the retrieveData UIButton it prints out "Found nil"
So if what I'm thinking is correct, its creating a coredata entry with an empty string, or nothing at all?
How can I fix this so that it creates a coredata entry with the string the user enters as the new pin, and also retrieves it later?
Your call to createPin needs to be inside the action handler for okAction. As you have it now, secondPinNumber will be called before the alert has been shown, so it will be empty or nil, depending on how you initialise it.
IBAction func createData(_ sender: Any) {
let enterPinAlertController = UIAlertController(title: "Enter New PIN", message: "", preferredStyle: .alert)
enterPinAlertController.addTextField{ (textField1:UITextField)->Void in
textField1.placeholder = "Enter PIN"
textField1.isSecureTextEntry = true
}
enterPinAlertController.addTextField{ (textField2:UITextField)->Void in
textField2.placeholder = "Re-Enter PIN"
textField2.isSecureTextEntry = true
}
let okAction = UIAlertAction(title: "OK", style: .cancel) {(action) in
if let textFields = enterPinAlertController.textFields,
let firstPinNumber = textFields[0].text,
let secondPinNumber = textFields[1].text,
firstPinNumber == secondPinNumber {
createPIN(pinNum: secondPinNumber)
} else {
print ("PINs dont match!")
let pinsDontMatchAlertController = UIAlertController(title: "PINs don't match!", message: "Try again", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel)
pinsDontMatchAlertController.addAction(okAction)
self.present(pinsDontMatchAlertController, animated: true, completion: nil)
}
}
}
enterPinAlertController.addAction(okAction)
self.present(enterPinAlertController, animated: true, completion: nil)
}
I want to display alert for check new version of my app from API. And from that view if userDefault data is store so base on that I want to redirect to another view. My redirection code is work perfectly but when I add alert code so redirection doesn't work. I think alert present in "self" and that time I also try to redirect from that view so it's may create problem. Here is my code..
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateUserData() //base on userDefault redirection
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
checkNewVersion() //Alert function for API calling
}
func checkNewVersion() -> Void {
//TODO: For check App new version
WebRequester.shared.getAppNewVersion { (result, error) in
if result != nil {
if result?.value(forKey: "status") as! Bool {
let strVer = (result?.object(forKey: "data") as! NSDictionary).object(forKey: "platform_version") as! String
if UserData.getAppVersion() < strVer {
let alert = UIAlertController(title: "Alert", message: "New version of App available", preferredStyle: .alert)
let ok = UIAlertAction(title: "Ok", style: .default, handler: { (action) in
})
let AppStore = UIAlertAction(title: "App Store", style: .default, handler: { (action) in
if let url = URL(string: "itms-apps://itunes.apple.com/app/id1024941703"),
UIApplication.shared.canOpenURL(url){
UIApplication.shared.openURL(url)
}
})
alert.addAction(ok)
alert.addAction(AppStore)
self.present(alert, animated: true, completion: nil)
// OperationQueue().addOperation {
// // Put queue to the main thread which will update the UI
// OperationQueue.main.addOperation({
// self.present(alert, animated: true, completion: nil)
// })
// }
}
}
else {
if (result?.object(forKey: "data") as! NSArray).object(at: 0) as? String ?? "" == "Unauthorised access." {
Model.shared.deleteAllCoreDataRecord(entity: "CartItem")
UIApplication.topViewController()?.navigationController?.popToRootViewController(animated: true)
}
let msg = result?.value(forKey: "data") as! [String]
Model.shared.showAlert(title: "Error", msg: msg[0], controller: self)
}
}
else {
Model.shared.showAlert(title: "Error", msg: error?.localizedDescription ?? "Something went wrong at add new address", controller: self)
}
}
}
func updateUserData() -> Void {
if UserData.getAppVersion() == "1.0" {
if UserData.getUserData() != nil {
//TODO: check for user Updated data
let params = ["mobile":UserData.getUserMobile()] as [String : Any]
let propic = UIImage(named: "temp")
weak var objWeek = self
Model.shared.showActivity(WithTouchEnable: false,controller: self)
WebRequester.shared.customerSignup(params: params as NSDictionary, proImg: propic!){ (result,error) -> Void in
Model.shared.HideActivity(controller: self)
if (error == nil) {
print("login result:",result ?? "")
//handle response of sign up
let statusstr = result?["status"] as! Bool
if (statusstr == false) {
//This condition for pepsi welcome offer is expire or not
let user = result!["user_info"] as! NSDictionary
self.storeUserData(user: user)
if UserData.getUserMobileNumVerify() == "No" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let registerScreen = storyboard.instantiateViewController(withIdentifier: "UserRegisterPhoneVC") as! UserRegisterPhoneVC
objWeek?.navigationController?.pushViewController(registerScreen, animated: true)
}
else {
if UserData.getPepsiOfferRedim() == "1" || UserData.getPepsiOfferRedim() == "2" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let offerScreen = storyboard.instantiateViewController(withIdentifier: "OfferViewController") as! OfferViewController
objWeek?.navigationController?.pushViewController(offerScreen, animated: true)
}
else {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let promoScreen = storyboard.instantiateViewController(withIdentifier: "PromotionViewController") as! PromotionViewController
objWeek?.navigationController?.pushViewController(promoScreen, animated: true)
}
}
}
}
}
else {
Model.shared.showAlert(title: "Error", msg: (error?.localizedDescription)!, controller: self)
}
}
}
}
}
To achieve this , you need to click on alert OK button then only it will automatically navigate to other controller , without this not possible .
Here is code :
Alert controller block help you to achieve this :
//show an alert and navigate to previous controller
let alertController: UIAlertController = UIAlertController(title: "Password updatd", message: "your alert message", preferredStyle: .alert)
let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in
//Redirect to new viewcontroler
let newVC = self.storyboard.instantiateViewcontroller(identifier: "newvc") as? NewVC
self.navigationController?.pushViewController(newVC,animated: true)
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
Feel free to comment. Thanks