我将API集成到Swift中相对较新。我有一个登录页面,我正在尝试对用户进行身份验证并在他们登录时创建会话。我在网上发现了一个可能适用于很多人的代码,但是我实际上无法完成整个工作。我已经得出结论,在这一行附近会出现问题,你将在下面的代码中看到,因为在它之前的行我能够获得身份验证令牌。
if let data_block = server_response["accessToken"] as? NSDictionary
我包含了所有相关代码,我想知道出了什么问题,如何成功验证和创建会话,以及让segue实际工作。
override func viewDidLoad() {
super.viewDidLoad()
_login_button = "Login"
let preferences = UserDefaults.standard
if(preferences.object(forKey: "session") != nil)
{
LoginDone()
}
else
{
LoginToDo()
}
}
@IBAction func signIn() {
let username = emailLoginTextField.text
let password = passwordLoginTextField.text
if(username == "" || password == "")
{
return
}
if(_login_button == "Logout")
{
let preferences = UserDefaults.standard
preferences.removeObject(forKey: "session")
LoginToDo()
return
} else {
DoLogin(username!, password!)
}
}
func DoLogin(_ user:String, _ psw:String)
{
let url = URL(string: "http://agile-castle-10059.herokuapp.com/authentication")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
let paramToSend = "username=" + user + "&password=" + psw + "&strategy=" + "local"
request.httpBody = paramToSend.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
guard let _:Data = data else
{
return
}
let json:Any?
do
{
json = try JSONSerialization.jsonObject(with: data!, options: [])
}
catch
{
return
}
guard let server_response = json as? NSDictionary else
{
return
}
//problem occurs around here, nothing happens (assuming the data_block isn't being created for some reason)
if let data_block = server_response["data"] as? NSDictionary
{
if let session_data = data_block["session"] as? String
{
let preferences = UserDefaults.standard
preferences.set(session_data, forKey: "session")
DispatchQueue.main.async (
execute:self.LoginDone
)
}
}
})
task.resume()
}
func LoginToDo()
{
_login_button = "Login"
}
func LoginDone()
{
self.shouldPerformSegue(withIdentifier: "showHomeViewControllerFromSignIn", sender: self)
_login_button = "Logout"
}
答案 0 :(得分:0)
我解决了一些事情并弄明白了
guard let server_response = json as? NSDictionary else
{
return
}
if let session_data = server_response["accessToken"] as? String
{
let preferences = UserDefaults.standard
preferences.set(session_data, forKey: "accessToken")
DispatchQueue.main.async (
execute:self.LoginDone
)
}
})
task.resume()
}