我对swift
很新,很抱歉,如果这是一个愚蠢的问题,但我自己无法找到解决方案。
我正在尝试在应用程序启动时检查红衣主教,并显示警告。
我的方法:
var apiRestManager = ApiRestManager()
override func viewDidAppear(_ animated: Bool) {
let defaults = UserDefaults.standard
if (defaults.value(forKeyPath: "testApp").debugDescription.characters.count > 2){
let usernamePassword = defaults.string(forKey: "testApp")
testCredinals(credinals: usernamePassword)
}
}
func testCredinals(credinals: String){
let isLoginCorrect: Bool
isLoginCorrect = apiRestManager.checkLogin(credinals: credinals)
if (isLoginCorrect){
showAlert(message: "ok")
}
else{
showAlert(message: "not ok")
}
}
func showAlert(message: String){
let alertController = UIAlertController(title: "iOScreator", message:
"response " + message, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
和我的ApiRestManager.swift
:
class ApiRestManager {
let apiURL = "http://localhost/api/"
let checkLoginMethod = "checklogin"
func checkLogin(credinals: String) -> Bool {
let loginData = credinals.data(using: String.Encoding.utf8)
let base64LoginString = loginData?.base64EncodedString()
let url = URL (string: apiURL + checkLoginMethod)
var request = URLRequest(url: url!)
request.httpMethod = "GET"
var responseResult: Bool
responseResult = false
request.setValue("Basic " + base64LoginString!, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
responseResult = true
}
}
task.resume()
return responseResult;
}
}
当我调试应用程序时,即使在调用API之前,也会显示带有消息not ok
的警报。如何检查响应然后有条件地显示警报?