I am using Swift 2 and Xcode 7.1.
I have a function that connects my users, but it will connect in my database with HTTP. I am using Alamofire to fulfill this request. I want to know from the controller point of view if the user is connected.
I have a connect function in a class. And I am testing the connection in ViewController. Like this:
class user {
func connectUser(username: String, password: String){
let urlHost = "http://localhost:8888/project350705/web/app_dev.php/API/connect/"
let parametersSymfonyG = [
username, password
]
let url = UrlConstruct(urlHost: urlHost).setSymfonyParam(parametersSymfonyG).getUrl()
Alamofire.request(.GET, url)
.responseString { response in
if let JSON = response.result.value {
var result = self.convertStringToDictionary(JSON)!
if result["status"] as! String == "success"{
let userArray = result["user"] as! [String:AnyObject]
userConnect = self.saveUser(userArray)
} else{
print("ERROR-CONNECTION :\n Status :\(result["status"]!)\n Code :\(result["code"]!)")
}
return ""
}
}
}
}
class MyViewController: UIViewController {
@IBAction func connect(sender: AnyObject?) {
User.connectUser(self.username.text!, password: self.password.text!)
if userConnect != nil {
print("connected")
}else{
print("NotConnected")
}
}
}
First decision: Return
This will require my function to return a boolean value. Only I can not use the refund.
Alamofire.request(.GET, url)
.responseString { response in
if let JSON = response.result.value {
var result = self.convertStringToDictionary(JSON)!
if result["status"] as! String == "success"{
let userArray = result["user"] as! [String:AnyObject]
userConnect = self.saveUser(userArray)
} else{
print("ERROR-CONNECTION :\n Status :\(result["status"]!)\n Code :\(result["code"]!)")
}
return ""
}
}
The second solution:
I can also check if the user has been registered, but before testing, I must wait for the function to load loaded.
users.connectUser(self.username.text!, password: self.password.text!)
if userConnect != nil {
print("connected")
}else{
print("NotConnected")
}
I would prefer to return a boolean. This will facilitate handling. Do you have a solution?
user5623030