我一直在研究iOS程序,而且我遇到了一些问题。我最近一直在测试一个使用GET方法登录的简单系统,但我需要使用POST来保证安全性,所以我切换了。错误发生在' if let dictionary'行,错误是它试图打开一个nil可选。虽然它具有完全相同的数据,但它仍然不起作用。想法?提前谢谢。
的iOS:
class ViewController: UIViewController {
var json: NSMutableData = NSMutableData()
var data: [[String: String]]!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBAction func attemptLogin(sender: UIButton) {
if(usernameTextField.text == "" || passwordTextField.text == "") {
var alert = UIAlertController(title: "Error", message: "Invalid Credentials", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
attemptConnection(usernameTextField.text, password: passwordTextField.text)
}
}
func parseJSON(inputData: NSData) -> [[String: String]]{
var error: NSError?
var dictionary: [[String: String]]!
if (inputData.length != 0) {
if let dictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? [[String: String]] {
} else {
}
}
return dictionary
}
override func viewDidLoad() {
super.viewDidLoad()
var tapBackground: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard:")
tapBackground.numberOfTapsRequired = 1;
self.view.addGestureRecognizer(tapBackground)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func dismissKeyboard(sender: AnyObject) {
self.view.endEditing(true)
}
func attemptConnection(username: String, password: String){
let urlPath: String = "https://codekaufman.com/getusers.php"
var url: NSURL = NSURL(string: urlPath)!
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
let bodyData = ("username=" + usernameTextField.text + "&password=" + passwordTextField.text as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = bodyData
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
activityIndicator.startAnimating()
self.view.userInteractionEnabled = false
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.json.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
activityIndicator.stopAnimating()
self.view.userInteractionEnabled = true
data = parseJSON(json)
println(data.count)
if(data.count != 0) {
self.performSegueWithIdentifier("login", sender: self)
println(data[0])
println(data[0]["first_name"]!)
} else {
self.view.backgroundColor = UIColor.redColor()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "login") {
var svc = segue.destinationViewController as SecondViewController;
svc.data = self.data
}
}
}
PHP:
try {
$dbh = new PDO('mysql:host=localhost; dbname=codeggdj_users', $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$recievedUsername = $_POST['username'];
$recievedPassword = $_POST['password'];
$sth = $dbh->prepare('SELECT password FROM users WHERE username = ?');
$sth->execute([$recievedUsername]);
if($sth->rowCount()) {
$row = $sth->fetch(PDO::FETCH_OBJ);
if(password_verify($recievedPassword, $row->password)) {
$sth = $dbh->prepare('SELECT id, username, first_name, last_name FROM users WHERE username = ?');
$sth->execute([$recievedUsername]);
echo json_encode($row = $sth->fetchAll(PDO::FETCH_ASSOC));
} else {
echo 'Incorrect Password';
}
} else {
echo 'Incorrect Username';
}
} catch(PDOException $e) {
echo $e->getMessage();
}