I'm trying to make a password protected view controller.
so far -
Created storyboard -
on viewcontroller - created hard coded log in -
prints to console if successful or not.
textfields etc...
#IBOutlet weak var untext: UITextField!
#IBOutlet weak var pwtext: UITextField!
let username = "admin"
let password = "adminpw"
override func viewDidLoad() {
super.viewDidLoad()
pwtext.isSecureTextEntry = true
}
#IBAction func loginbtn(_ sender: Any) {
if untext.text == username && pwtext.text == password
{
print("log in succesful")
} else {
print("log in failed")
}
}
The issue I have, once I press the login button, it takes me to the admin page if successful or not.
How can I print a notification - on screen - if unsuccessful and remain on the current view controller, and if successful, take me to admin view controller?
You can either use a segue or instantiateViewController. But in this example I'll use instantiateViewController (Images). (But commented how to use a segue)
Add a class and an identifier to your secondary ViewController
Choose between my Segue or Instantiate. (Check my comments in the code)
If login is succeeded, either perform the segue or navigate using instantiate.
Happy coding. :D
But first off, let's take a look at the code you provided.
#IBAction func loginbtn(_ sender: Any)
{
if untext.text == username && pwtext.text == password
{
print("login succeeded")
//1. using instantiateViewController
if let storyboard = storyboard
{
//Check my image below how to set Identifier etc.
// withIdentifier = Storyboard ID & "ViewController" = Class
let vc = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.present(vc, animated: false, completion: nil)
}
//2. Use segue (I'll wrap this with a comment incase you copy)
//self.performSegue(withIdentifier: "SegueID", sender: self)
}
else
{
//Setting up an "AlertController"
let alert = UIAlertController(title: "Login failed", message: "Wrong username / password", preferredStyle: UIAlertController.Style.alert)
//Adding a button to close the alert with title "Try again"
alert.addAction(UIAlertAction(title: "Try again", style: UIAlertAction.Style.default, handler: nil))
//Presentating the Alert
self.present(alert, animated: true, completion: nil)
}
}
Click on the yellow dot on your ViewController (On the ViewController where you want the login-page to take you)
Click on the icon like I've. (Which is blue) and set a Class + Storyboard ID.
NOTE! IF you wanna use a segue, make SURE you have a connection between ViewController(Login) and ViewController1
Assuming you use segues for navigation, you can put a "general purpose" segue (drag from your controller, instead of any controls in it) and assign it an ID (Identifier in attribute inspector of the segue in Storyboard). After that you can conditionally invoke segue from the parent controller class with your code:
if passwordCorrect {
performSegue(withIdentifier: "SegueID", sender: nil)
}
Related
My app has a "Create Account" view controller (shown below) that prompts the user to enter a username and password. Whenever I segue to another view controller, I get a pop-up action sheet prompting to save the password in the keychain.
This is a nifty little freebie IF the user successfully creates the new account. But I get this same pop-up if the user hits the cancel (back) button in the navigation bar, if they select the option to use Facebook login instead of creating an account, or any other means for leaving this view controller (see figures below).
How can I get this popup to ONLY show up when the user successfully creates a new account?
EDIT: Per request, here is the code that is related to the segues that result in the appearance of the "Save Password" action sheet.
from CreateAccountViewController.swift:
class CreateAccountViewController : UIViewController
{
// ... bunch of irrelevant code deleted ...
// bound to "Connect with Facebook" button (see image below)
#IBAction func switchToFacebook(_ sender : UIButton)
{
performSegue(.SwitchToFacebookLogin, sender: sender)
}
// ... bunch of irrelevant code deleted ...
}
extension CreateAccountViewController : GameServerAlertObserver
{
// callback based on response from GameCenter after
// submitting a "create new user" request
func handleConnectionResponse(_ response:GameServerResponse )
{
switch response
{
// ... other response cases removed ...
case .UserCreated:
self.removeSpinner()
performSegue(.CreateAccountToStartup, sender: self)
default:
response.displayAlert(over: self, observer: self)
self.removeSpinner()
}
}
// Functions defined in the GameServerAlertObserver protocol
// to handle user response to "User Exists Popup" (figure below)
func ok()
{
// user chose to enter new password... clear the existing username field
usernameTextField.text = ""
}
func cancel()
{
// segue back to the startup view controller
performSegue(.CreateAccountToStartup, sender: self)
}
func goToLogin()
{
// segue to the login view controller
performSegue(.SwitchToAccountLogin, sender:self)
}
}
from UIViewController_Segues:
enum SegueIdentifier : String
{
case LoserBoard = "loserBoard"
case CreateAccount = "createAccount"
case AccountLogin = "accountLogin"
case FacebookLogin = "facebookLogin"
case SwitchToFacebookLogin = "switchToFacebookLogin"
case SwitchToAccountLogin = "switchToAccountLogin"
case CreateAccountToStartup = "createAccountToStartup"
case AccountLoginToStartup = "accountLoginToStartup"
case FacebookLoginToStartup = "facebookLoginToStartup"
case UnwindToStartup = "unwindToStartup"
}
extension UIViewController
{
func performSegue(_ target:SegueIdentifier, sender:Any?)
{
performSegue(withIdentifier: target.rawValue, sender: sender)
}
}
from GameServerAlert.swift:
protocol GameServerAlertObserver
{
func ok()
func cancel()
func goToLogin()
}
extension GameServerResponse
{
func displayAlert(over controller:UIViewController, observer:GameServerAlertObserver? = nil)
{
var title : String
var message : String
var actions : [UIAlertAction]
switch self
{
// ... deleted cases/default which don't lead to segue ...
case .UserAlreadyExists:
title = "User already exists"
message = "\nIf this is you, please use the login page to reconnect.\n\nIf this is not you, you will need to select a different username."
actions = [
UIAlertAction(title: "Go to Login page", style: .default, handler: { _ in observer?.goToLogin() } ),
UIAlertAction(title: "Enter new username", style: .default, handler: { _ in observer?.ok() } ),
UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in observer?.cancel() } )
]
}
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
actions.forEach { (action) in alert.addAction(action) }
controller.present(alert,animated:true)
}
}
Examples from the simulator:
Create Account - (user enters username and password for new account here.)
Facebook Login
If user decides to use Facebook to log in rather than creating a user account, they are taken to this view (which I still haven't fleshed out). Note that the "Save Password" action sheet has popped up.
User Exists Popup
If user attempts to create an account with a username that already exists, they will be presented with this popup. If they select Cancel, they are taken back to the startup screen (see below). If they select Enter new username, they are kept on the same screen with the username cleared out. If they select Login, they are taken to the login screen.
Startup Screen
If the user selects Cancel above, they are brought back here. Again, note that the "Save Password" action sheet has popped up.
What I do to avoid the automatic Password saving action sheet when the user :
dismiss the login view controller ;
pop the view controller ;
use interactive pop gesture.
=>
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
passwordTextField.textContentType = .password
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if isMovingFromParent || isBeingDismissed || parent?.isBeingDismissed == true {
passwordTextField.textContentType = nil
}
}
Sorry about the short answer, I don't usually post on this site. This is the password Autofill that is happening on your device when the create user screen is dismissed.
Apple Documentation: https://developer.apple.com/documentation/security/password_autofill
Here is a link to a site that goes over all the requirements very well: https://developerinsider.co/ios12-password-autofill-automatic-strong-password-and-security-code-autofill/
Add a condition before running the code block which shows the action sheet. You can do this simply with an if statement. This statement must check if the account has been successfully created or not. Code block which shows action sheet must run only when the condition is true.
The problem here is that I'm presenting EditCommentVC modally, over the current context of the CommentVC because I want to set the background of the UIView to semi-transparent. Now, on the EditCommentVC I have a UITextView that allows the user to edit their comment, along with 2 buttons - cancel (dismisses the EditCommentVC) and update that updates the new comment and push it to the database.
In term of code, everything is working, except that once the new comment is being pushed and EditCommentVC is being dismissed, the UITableView on CommentsVC with all the comments is not being reloaded to show the updated comments. Tried calling it from viewWillAppear() but it doesn't work.
How can I reload the data in the UITableView in this case?
#IBAction func updateTapped(_ sender: UIButton) {
guard let id = commentId else { return }
Api.Comment.updateComment(forCommentId: id, updatedComment: editTextView.text!, onSuccess: {
DispatchQueue.main.async {
let commentVC = CommentVC()
commentVC.tableView.reloadData()
self.dismiss(animated: true, completion: nil)
}
}, onError: { error in
SVProgressHUD.showError(withStatus: error)
})
}
The code in the CommentVC where it transitions (and passes the id of the comment). CommentVC conforms to a CommentActionProtocol that passes the id of that comment:
extension CommentVC: CommentActionProtocol {
func presentActionSheet(for commentId: String) {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let editAction = UIAlertAction(title: "Edit", style: .default) { _ in
self.performSegue(withIdentifier: "CommentVCToEditComment", sender: commentId)
}
actionSheet.addAction(editAction)
present(actionSheet, animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "CommentVCToEditComment" {
let editCommentVC = segue.destination as! EditCommentVC
let commentId = sender as! String
editCommentVC.commentId = commentId
}
}
}
I see atleast 2 problems here:
You are creating a new CommentVC which you should not do if you want to update the tableView in the existing view controller.
Since you have mentioned that Api.Comment.updateComment is a an asynchronous call, you need to write the UI code to run on the main thread.
So first you need to have the instance of the commentVC in a variable inside this viewController. You can store the instance of the view controller from where you are presenting this view controller.
class EditCommentVC {
var commentVCdelegate: CommentVC!
// Rest of your code
}
Now you need to pass the reference commentVC in this variable when you are presenting the edit view controller.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "CommentVCToEditComment" {
let editCommentVC = segue.destination as! EditCommentVC
let commentId = sender as! String
editCommentVC.commentId = commentId
editCommentVC.commentVCdelegate = self
}
}
Now you need to use this reference to reload your tableView.
Api.Comment.updateComment(forCommentId: id, updatedComment: editTextView.text!, onSuccess: {
DispatchQueue.main.async {
commentVCdelegate.tableView.reloadData() // - this commentVC must be an instance that you store of the your commentVC that you created the first time
self.dismiss(animated: true, completion: nil)
}
}, onError: { error in
SVProgressHUD.showError(withStatus: error)
})
Well, i had this problem too, and the solution i found was to use Protocol. I would recommend you to search how to send data back to previous ViewController. That way, when you dismiss the EditCommentVC, you then send back a value(in my case i send true) to the previous ViewController(in your case, CommentVC), and then you'll have a function in CommentVC checking if the value is true and if it is, reload the TableView.
Here, let me show you an example of how i used (those are the names of my ViewControllers, functions and protocols, you can use whatever you want and send whatever data you want back):
In your CommentVC, you'll have something like this:
protocol esconderBlurProtocol {
func isEsconder(value: Bool)
}
class PalestranteVC: UIViewController,esconderBlurProtocol {
func isEsconder(value: Bool) {
if(value){
//here is where you can call your api again if you want and reload the data
tableView.reloadData()
}
}
}
Also, dont forget that you have to set the delegate of EditCommentVC, so do it when you're presenting EditCommentVC, like this:
let viewController = (self.storyboard?.instantiateViewController(withIdentifier: "DetalhePalestranteVC")) as! DetalhePalestranteVC
viewController.modalPresentationStyle = .overFullScreen
viewController.delegate = self
self.present(viewController, animated: true, completion: nil)
//replace **DetalhePalestranteVC** with your **EditCommentVC**
And in your EditCommentVC you'll have something like this:
class DetalhePalestranteVC: UIViewController {
var delegate: esconderBlurProtocol?
override func viewWillDisappear(_ animated: Bool) {
delegate?.isEsconder(value: true)
}
}
That way, everything you dismiss EditCommentVC, you'll send back True and reload the tableView.
Guys i am facing an odd problem with NavigationController. Existing answers did not help at all !!!!
Here is basic scenario of the app:
There are two views - Main and Second view
In main view there is a button when i happen to tap goes into second view using segue.
In second view after i enter a certain field in text view and click on a button called "join" it triggers "joinMeeting()" function
and meeting should be joined.
However, when i do that debugger shows me:
"Warning: Attempt to present on
<***.ViewController: *****> whose view is not in the window
hierarchy!"
So i have read most of the tread and given that it happens because of viewDidAppear method but i have nth to be done before viewDidAppear. Everything happens after button is clicked.
joinMeeting() is successfully called and print method returns 0 which means no issue(https://developer.zoom.us/docs/ios/error-codes/) and successful SDK connection however after this "Warning" error is shown in debugger and nothing happens in the app.
If it helps following is the code that triggers joinBtn:
/**
Triggers when Join Button is clicked from second view.
*/
#IBAction func joinMeeting(_ sender: Any) {
if( activityID.text == "" ) {
let alert = UIAlertController(title: "Field is Blank", message: "Activity ID cannot be blank.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
return;
}
let ms: MobileRTCMeetingService? = MobileRTC.shared().getMeetingService()
if ms != nil {
ms?.delegate = self;
// //For Join a meeting
let paramDict: [AnyHashable: Any] = [
kMeetingParam_Username: kSDKUserName,
kMeetingParam_MeetingNumber: activityID.text!,
]
let ret: MobileRTCMeetError? = ms?.joinMeeting(with: paramDict)
print("onJoinaMeeting ret:\(String(describing: ret))")
}
}
Please help if anyone knows or have an idea on what i am missing here.
Here is what solved the issue:
Storyboard Configuration:
ViewController --Segue: Show--> JoinViewController
#IBAction func onClickJoin(_ sender: AnyObject) {
//Main storyBoard
let initialVC = UIStoryboard(name: "Main", bundle:nil).instantiateInitialViewController() as! UIViewController
let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
appDelegate.window?.rootViewController = initialVC
//Rest of the code
}
Just Add Following code on that controller in which you want to perform calling:
override func viewWillAppear(_ animated: Bool) {
let appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate?.window?.rootViewController = self
}
Unfortunately, none of the above solutions worked for me.
So Here is my solution.
Add this line
MobileRTC.shared().setMobileRTCRootController( self.navigationController)
=> When user taps of Join Call Button.
Make sure these conditions should meet as well.
ViewController which is used to open the ZOOM meeting should be a part of root navigation controller
DO NOT present modally the current Zoom Meeting Joining View Controller. Always push it to the root navigation controller.
I am trying to building a app using the master details template.
in the Master view controller I added a button called Catalogue : this button showing a tabbar controller called Catalogue.
I don't use Segue to show the catalogue, I use the code below to show the tab controller
From Master form I called the Tabbar controller :
#IBAction func Btn_Catalogue(_ sender: Any) {
let AddCatalogueVC = self.storyboard?.instantiateViewController(withIdentifier: "CatalogueVC") as! CatalogueVC
present(AddCatalogueVC, animated: true, completion: nil)
}
From CategorieVC I use the code below to show
#IBAction func Btn_AddCategorie(_ sender: Any) {
self.Mode = "New"
let AddCategorieViewController = self.storyboard?.instantiateViewController(withIdentifier: "AddCategorieVC") as! AddCategorieVC
present(AddCategorieViewController, animated: true, completion: nil)
}
I dismiss the AddCategorieVC using the code below
#IBAction func Btn_Save(_ sender: Any)
{
if self.Txt_CategorieName.text != ""{
self.Mysave = true
self.MyCategorieName = self.Txt_CategorieName.text!
self.dismiss(animated: true, completion: nil)
}
}
I have unwind SEGUE from Save button to a function in categorieVC
#IBAction func FctSaveCategories(_ sender: UIStoryboardSegue) {
let sendervc = sender.source as! AddCategorieVC
if self.Mode == "New" && sendervc.Mysave == true { // Mode insert
let MyCategories = TblCategorie(context: Mycontext)
MyCategories.categorie_Name = sendervc.MyCategorieName
do {
try Mycontext.save()
} catch {
debugPrint ("there is an error \(error.localizedDescription)")
}
}
}
The problem is when I hit the save button in categorieVC the catalogueVC is also dismissing at the same time returning me to the master control.
I am almost sure that the problem came from the Unwind segue but I don't know why.
Update: I activate the Cancel button in AddCategorieVC with the code below
self.dismiss(animated: true, completion: nil)
and when I clicked on it only the AddCategorieVC is being dismissed and I go back to CatalogueVC. The difference between the save button and the Cancel Button is only the UNWIND segue on the Save Button.
And when I add UnWIND segue to the cancel Button (just to test the behavior) it took me back to the master form instead CatalogueVC.
How can I solve that?
And yesss I found it
It look like that unwind segue automaticly handled dismiss contrĂ´le
So all I need to do is remove the dismiss code from the save button this way the unwind segue will took me back to catalogueVC.
.
I am new to Swift and iOS development. I have been trying to create an app-wide check for internet connectivity, that allows the user to retry (reload the current view). The checkInternetConnection() function below is called during viewWillAppear() in my BaseUIViewController class.
The Reachability.isConnectedToNetwork() connectivity-check works fine. But so far, I have not been able to figure out a way to reload the current view after the user presses the 'Retry' button in the alert. in fact, I have not been able to figure out a way to reload the current view in any scenario.
One thing I know I am doing wrong in the following attempt (since there is a compile error telling me so), is that I am passing a UIViewController object as a parameter instead of a string on this line: self.performSegueWithIdentifier(activeViewController, sender:self), but I suspect that this is not my only mistake.
func checkInternetConnection() {
if (Reachability.isConnectedToNetwork()) {
print("Internet connection OK")
} else {
print("Internet connection FAILED")
let alert = UIAlertController(title: NSLocalizedString("Error!", comment: "Connect: error"), message: NSLocalizedString("Could not connect", comment: "Connect: error message"), preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Retry", comment: "Connect: retry"), style: .Default, handler: { action in
print("Connection: Retrying")
let navigationController = UIApplication.sharedApplication().windows[0].rootViewController as! UINavigationController
let activeViewController: UIViewController = navigationController.visibleViewController!
self.performSegueWithIdentifier(activeViewController, sender:self)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
BaseUIViewController can perform app-wide check for connectivity, so all your ViewControllers will be inherited from BaseUIViewController.
And each ViewController will have different behaviour after connectivity check.
One thing you can do is, in your BaseUIViewController you can define a block that performs action after connectivity check failed.
Here's the example:
class BaseViewUIController: UIViewController {
var connectivityBlock: (() -> Void)?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
checkInternetConnection()
}
func checkInternetConnection() {
if Reachability.isConnectedToNetwork() {
print("Internet connection OK")
} else {
if let b = connectivityBlock {
b()
}
}
}
}
And in your inherited ViewControllers:
class MyViewController: BaseUIViewController {
override func viewDidLoad() {
super.viewDidLoad()
connectivityBlock = {
print("Do View Refresh Here.")
}
}
}
Then After the check in BaseUIViewController, the code in connectivityBlock will be executed so that each VC can deal with it differently.
You can also define a function in BaseUIViewController and each subclass will override that function, after connectivity check failed, call the function.
Try navigate using application's windows
let destinationVC = UIApplication.shared.delegate?.window
destinationVC .present(activeViewController, animated: true, completion: nil)