目前正在开发一个需要 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/