Swift HTTP POST 登录验证

标签 swift authentication swift3 http-post

目前正在开发一个需要 HTTP POST 方法与服务器通信的 iOS 应用程序。获取用户名和密码是否正确是成功的,但是服务器返回的是字符串 例如:

如果用户名和密码正确:

<string> Correct </string>

如果用户名或密码不正确:

<string> Incorrect </string>

如何添加验证,如下所示: 如果当前用户名和密码正确,则转到下一个 ViewController,但如果当前用户名或密码不正确,则显示错误消息而不转到下一个 ViewController。

这是我使用的代码:

import UIKit


class ViewController: UIViewController {
    @IBOutlet var passwordField: UITextField!
    @IBOutlet var usernameField: UITextField!


override func viewDidLoad() {
        super.viewDidLoad()

           }

    @IBAction func LoginGetData(_ sender: Any) {


        var request = URLRequest(url: URL(string: "http://mylinkinhere")!)
        request.httpMethod = "POST"
        let postString = "username=\(usernameField.text!)&password=\(passwordField.text!)"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print("error=\(error)")
                return
            }

             let httpStatus = response as? HTTPURLResponse
                print("statusCode should be 200, but is \(httpStatus!.statusCode)")
                print("response = \(response)")
                print(postString)

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")

        }
        task.resume()
    }
}

谢谢。

最佳答案

您的 API 响应是 application/xml 而不是 application/json,但是对于此响应您可以使用 contains 并检查它是否正确或不正确。所以在得到响应后尝试这样。

let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")

if (responseString?.contains("Incorrect")) {
    DispatchQueue.main.async {
        print("incorrect - try again")
        let alert = UIAlertController(title: "Try Again", message: "Username or Password Incorrect", preferredStyle: UIAlertControllerStyle.alert)                    
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))                                        
        self.present(alert, animated: true, completion: nil)
    }
}                
else {
    DispatchQueue.main.async {
        print("correct good")

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "correctone")
        self.present(controller, animated: true, completion: nil)
    }
}

关于Swift HTTP POST 登录验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41331318/

相关文章:

swift - 如何使用 init 变量在 swift 中创建单例

java - 使用 OAuth 的 Google App Engine 身份验证

authentication - "Logout"来自 Notes 身份验证

ios - Swift:从 Swift 2 到 Swift 3 的转换失败

ios - 使用导航 Controller 作为发送者

iphone - 如何使用 UITextAlignment 将 UITableViewCell 中的文本在 Swift 中左右对齐

ios - CoreData 搜索速度太慢

c# - HTTP 处理程序的相同 Asp.net 表单例份验证

ios - 如何使用来自 xcdatamodeld 的 Fetch 请求?

ios - 在 UITabBarController 内部,如何从一个 View Controller 切换到另一个 View Controller 并保留选项卡栏?