完成加载后,将按钮更改为默认值

问题描述 投票:0回答:2

我正在尝试在登录时将按钮从登录状态更改为登录状态,但如果UI警告显示错误密码则要返回默认状态“登录”

         isChecked = !isChecked
    if isChecked {
        sender.setTitle("login", for: .normal)

    } else {
        sender.setTitle("logging", for: .normal)

这是完整的代码,我把警报放在else语句但是添加断点仍然无法正常工作

   import UIKit
   import SwiftECP
   import XCGLogger
  class ViewController: UIViewController {
 var isChecked = true
@IBOutlet var UsernameField: UITextField!
@IBOutlet var passwordField: UITextField!
@IBOutlet var login: UIButton!

  var file1 = "file.txt"

override func viewDidLoad() {
    super.viewDidLoad()
    login.layer.cornerRadius = login.frame.height / 2
    var img = UIImage(named: "1.jpg")
    view.layer.contents = img?.cgImage

  }

@IBAction func _Login(_ sender: UIButton) {


    let isFirstNameValid = checker(textField:UsernameField)
    let ispasswordValid = checker(textField:passwordField)

    isChecked = !isChecked
    if isChecked {
        sender.setTitle("login", for: .normal)

    } else {
        sender.setTitle("logging", for: .normal)
    }
    print ("text field \(isFirstNameValid)")

    if isFirstNameValid && ispasswordValid == true {
        gotourl()

        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            let readf = self.readFromDocumentsFile(fileName:self.file1)
            let sizefile = self.filesize(fileName:self.file1)
            if sizefile == true{
                self.performSegue(withIdentifier: "gotowelcome", sender: self)

             }
            else
            {
                let alert = UIAlertController(title: "Login error", message: "Wrong Username or password.", preferredStyle: UIAlertControllerStyle.alert)

                // add an action (button)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.destructive, handler: { action in
                    self.login.setTitle("Login", for: .normal)
                    self.UsernameField.text=""
                    self.passwordField.text=""

                }))
                // show the alert
                self.present(alert, animated: true, completion: nil)

             }

            print("Here is the size of file \(sizefile)")
            // change 2 to desired number of seconds
            // Your code with delay
         }

      }
    else  {

        let alert1 = UIAlertController(title: "Login error", message: "Please enter your username and password", preferredStyle: UIAlertControllerStyle.alert)

        // add an action (button)
        alert1.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        self.present(alert1, animated: true, completion: nil)
    }


  }

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
   }


func gotourl(){

let username1: String = UsernameField.text!
let password1: String = passwordField.text!
let protectedURL = URL(
    string: "https://itsapps.odu.edu/auth/getInfo.php"
    )!
let logger = XCGLogger()
logger.setup(level: .debug)

ECPLogin(
    protectedURL: protectedURL,
    username: username1,
    password: password1,
    logger: logger
    ).start { event in
        switch event {

        case let .value( body) :
            // If the request was successful, the protected resource will
            // be available in 'body'. Make sure to implement a mechanism to
            // detect authorization timeouts.

            print("Response body: \(body)")

            //this is the file. we will write to and read from it

            let text = "\(body)" //just a text
            self.writeToDocumentsFile(fileName:self.file1,value:text)


            // The Shibboleth auth cookie is now stored in the sharedHTTPCookieStorage.
            // Attach this cookie to subsequent requests to protected resources.
            // You can access the cookie with the following code:
            if let cookies = HTTPCookieStorage.shared.cookies {
                let shibCookie = cookies.filter { (cookie: HTTPCookie) in
                    cookie.name.range(of: "shibsession") != nil
                    }[0]
                print(shibCookie)
             }

        case let .failed(error):
            // This is an AnyError that wraps the error thrown.
            // This can help diagnose problems with your SP, your IdP, or even this library :)

            switch error.cause {
            case let ecpError as ECPError:
                // Error with ECP
                // User-friendly error message
                print(ecpError.userMessage)

                // Technical/debug error message
                print(ecpError.description)
            case let alamofireRACError as AlamofireRACError:
                // Error with the networking layer
                print(alamofireRACError.description)
            default:
                print("Unknown error!")
                print(error)

            }

        default:
            break

        }
  }

  }

func filesize(fileName:String) -> Bool {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
    let path = documentsPath.appendingPathComponent(fileName)
    let attributes = try! FileManager.default.attributesOfItem(atPath:path)
    let fileSize = attributes[.size] as! NSNumber
    if fileSize != 0 {
        return true
    }
    else{
        return false
    }

  }

func checker(textField: UITextField) -> Bool {
    guard (!textField.text!.isEmpty) else {
        return false
    }
    return true
  }
func writeToDocumentsFile(fileName:String,value:String) {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
    let path = documentsPath.appendingPathComponent(fileName)
    do{
        try value.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)

    }catch{
    }
    }

func readFromDocumentsFile(fileName:String) -> String {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
    let path = documentsPath.appendingPathComponent(fileName)
    let checkValidation = FileManager.default
    var file:String

    if checkValidation.fileExists(atPath: path) {
        do{
            try file = NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String
            print ("Here is what is in file \(file)")
        }catch{
            file = ""
        }
    } else {
        file = ""
    }

    return file
 }


}


    }

在我的代码的另一部分

 let alert = UIAlertController(title: "Login error", message: "Wrong Username or password.", preferredStyle: UIAlertControllerStyle.alert)
 alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.destructive, handler: { action in
                    self.UsernameField.text=""
                    self.passwordField.text=""
                    sender.setTitle("login", for: .normal)

                }))

但仍然没有工作任何原因?

ios swift
2个回答
0
投票

我认为这是因为你失去了对按钮的引用,并且必须在弹出窗口出现时再次加载或者像这样的时候发生类似的事情。

由于有两个状态,只有一个简单的解决方案是让按钮的默认文本为“login”,当你想要更改它时,不要在闭包中这样做,因为它是一个弱插座。


0
投票

你有警报吗?我添加后,上面的代码对我有用

self.present(alert, animated: true, completion: nil)

完整代码:

@IBAction func loginFailedButtonTapped(_ sender: UIButton) {
        let alert = UIAlertController(title: "Login error", message: "Wrong Username or password.", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.destructive, handler: { action in
            self.usernameField.text=""
            self.passwordField.text=""
            print("foo")
            sender.setTitle("login", for: .normal)
        }))
        self.present(alert, animated: true, completion: nil)
    }

更新:

It looks like the issue is there in the following lines:
let sizefile = self.filesize(fileName:self.file1)
                if sizefile == true{
                    self.performSegue(withIdentifier: "gotowelcome", sender: self)

                }
                else
                {
                    let alert = UIAlertController(title: "Login error", message: "Wrong Username or password.", preferredStyle: UIAlertControllerStyle.alert)

                    // add an action (button)
                    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.destructive, handler: { action in
                        self.login.setTitle("Login", for: .normal)
                        self.UsernameField.text=""
                        self.passwordField.text=""

                    }))

如果我设置let sizefile = false //self.filesize(fileName:self.file1)

代码确实转到了else,警报按要求工作。

警报控制器没有问题,似乎func filesize(fileName:String)总是返回true,因此它永远不会进入其他条件。你需要修复这个功能。

© www.soinside.com 2019 - 2024. All rights reserved.