@IBAction func loginBtnPressed(_ sender: AnyObject) {
let userID = self.userName.text! as String
let password = self.passwordText.text! as String
if userID.isEmpty || password.isEmpty {
showMessage(myMessage: "username & password required")
return
}
let postsEndpoint: String = "http://xxx/api/login/"
let newPost = ["username": userID, "password": password] as [String : Any]
Alamofire.request(postsEndpoint, method: .post, parameters: newPost, encoding: URLEncoding.httpBody)
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling GET on /posts/1")
print(response.result.error!)
return
}
if let value: AnyObject = response.result.value as AnyObject? {
// handle the results as JSON, without a bunch of nested if loops
let post = JSON(value)
print("The User is: " + post.description)
let username = post["display_name"].string
if ( username != nil ) {
// to access a field:
// print("The title is: " + username!)
let sb: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let controllerLogin : UIViewController = sb.instantiateViewController(withIdentifier: "logInSB")
self.present(controllerLogin, animated: true, completion: nil)
} else {
self.showMessage(myMessage: "wrong username & password")
}
}
}
}
我知道会话& cookies 是,如果有些人告诉我如何使用 Alamofire & 斯威夫特这对我来说会更加节省生命。我在网上搜索但找不到合适的答案。先感谢您。
答案 0 :(得分:-1)
自己解决了。在我的 loginBtnPressed 功能我设置了一些键,就像这样
UserDefaults.standard.set(post["user_id"].int, forKey: "user_id")
UserDefaults.standard.set(post["user_email"].stringValue, forKey: "user_email")
UserDefaults.standard.set(post["display_name"].stringValue, forKey: "display_name")
UserDefaults.standard.synchronize()
最后在 AppDelegate 中我检查并调用它如下所示
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UIApplication.shared.statusBarStyle = .lightContent
let getUserID = UserDefaults.standard.string(forKey: "user_id")
if getUserID != nil {
let sb: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let controllerLogin : UIViewController = sb.instantiateViewController(withIdentifier: "SWRevealViewController") as! SWRevealViewController
self.window?.rootViewController = controllerLogin
}
return true
}