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

时间:2018-04-12 14:40:57

标签: ios swift

iam在加载时尝试将我的按钮从登录更改为登录,但如果出现错误密码的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)

                }))

但仍然无法正常工作?

2 个答案:

答案 0 :(得分:0)

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

由于有两种状态,只有一个简单的解决方案是使按钮的默认文本为" login"当你想改变它时,不要在关闭时这样做,因为它是一个弱的出口。

答案 1 :(得分: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)

代码确实转到了其他地方,警报按要求运行

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