我正在创建一个登录应用程序,当我找到一种向php发送POST请求的方法,并且我尝试它时,有错误或没有错误但不运行我的PHP脚本。提前致谢。我在OS X El Capitan上使用带有XCODE 7和Swift 2的mac。我的服务器是带有WAMPServer的老式Windows PC。
import UIKit
class Login: UIViewController {
@IBOutlet weak var UserName: UITextField!
@IBOutlet weak var PassWord: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
UserName.resignFirstResponder()
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
@IBAction func LoginTapped(sender: AnyObject) {
var UserNameEntered = UserName.text
var PassWordEntered = PassWord.text
let ClientUserNameStored = NSUserDefaults.standardUserDefaults().stringForKey("UserName");
let ClientPassWordStored = NSUserDefaults.standardUserDefaults().stringForKey("PassWord");
if(ClientUserNameStored != UserNameEntered && PassWordEntered != ClientPassWordStored || ClientUserNameStored != UserNameEntered && PassWordEntered == ClientPassWordStored || ClientUserNameStored == UserNameEntered && ClientPassWordStored != PassWordEntered){
print("Not equal")
var Alert = UIAlertController(title: "Warning", message: "Invalid username or password!", preferredStyle: UIAlertControllerStyle.Alert)
Alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction!) in UserNameEntered = ""; PassWordEntered = "";
}))
presentViewController(Alert, animated: true, completion: nil)
}else{
let request = NSMutableURLRequest(URL: NSURL(string: "http://host/my/file.php")!)
request.HTTPMethod = "POST"
let postString = "username=\(UserNameEntered)&password=\(PassWordEntered)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
self.performSegueWithIdentifier("GoToHome", sender: self)
}
}
}
我的PHP代码如下。
<?php
$postVar = $_POST['username'];
$postVartwo = $_POST['password'];
$file = fopen("test.txt", "a");
echo fwrite($file, $postVar."pass".$postVartwo);
fclose($file);
?>
答案 0 :(得分:0)
执行任务后,执行后续操作。这意味着您将离开控制器和控制器将不再存在。没有强大的参考,这就是为什么不会调用你的响应块。
删除performSeque并重试。
答案 1 :(得分:0)
我没有允许我的应用使用HTTP。我通过添加
更改了我的info.plist<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>