这是我注册用户的快捷方式:
//Information fields
@IBOutlet weak var user: UITextField!
@IBOutlet weak var pass: UITextField!
@IBOutlet weak var pass2: UITextField!
@IBOutlet weak var name: UITextField!
@IBOutlet weak var email: UITextField!
@IBOutlet weak var Message: UILabel!
//Register button
@IBAction func register(_ sender: Any) {
let Parameters = ["username": user.text, "password": pass.text, "email": email.text, "name": name.text]
let url = URL(string: "http://cgi.soic.indiana.edu/~lvweiss/prof4/register.php")!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: Parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
Message.text = String(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
}
} catch let error {
print(error.localizedDescription)
self.Message.text = String(error.localizedDescription)
}
})
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
这是PHP:
<?php
require_once 'DbOperation.php';
$response = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!verifyRequiredParams(array('username', 'password', 'email', 'name'))) {
//getting values
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$name = $_POST['name'];
//creating db operation object
$db = new DbOperation();
//adding user to database
$result = $db->createUser($username, $password, $email, $name);
//making the response accordingly
if ($result == USER_CREATED) {
$response['error'] = false;
$response['message'] = 'User created successfully';
} elseif ($result == USER_ALREADY_EXIST) {
$response['error'] = true;
$response['message'] = 'User already exist';
} elseif ($result == USER_NOT_CREATED) {
$response['error'] = true;
$response['message'] = 'Some error occurred';
}
} else {
$response['error'] = true;
$response['message'] = 'Required parameters are missing';
}
} else {
$response['error'] = true;
$response['message'] = 'Invalid request';
}
//function to validate the required parameter in request
function verifyRequiredParams($required_fields)
{
//Looping through all the parameters
foreach ($required_fields as $field) {
//if any requred parameter is missing
if (!isset($_POST[$field]) || strlen(trim($_POST[$field])) <= 0) {
//returning true;
return true;
}
}
return false;
}
echo json_encode($response);
?>
以下是我尝试发布到数据库的信息: iOS注册字段:
我在点击注册按钮时从Xcode收到的错误:
2017-11-14 00:42:01.529344-0500 WeissProf4 [8754:662299] [MC]懒加载 NSBundle MobileCoreServices.framework
2017-11-14 00:42:01.530670-0500 WeissProf4 [8754:662299] [MC]已加载MobileCoreServices.framework
2017-11-14 00:42:01.550941-0500 WeissProf4 [8754:662299] [MC] systemgroup.com.apple.configurationprofiles路径的系统组容器是/ Users / leviweiss / Library / Developer / CoreSimulator / Devices / C98EE410-1CA2 -4B4B-9ED8-A4F112C629E2 /数据/容器/共享/ SystemGroup / systemgroup.com.apple.configurationprofiles
2017-11-14 00:42:03.468653-0500 WeissProf4 [8754:662299] [MC]从私人有效用户设置中读取。
2017-11-14 00:42:04.769899-0500 WeissProf4 [8754:662505] [MC]缓存无效
2017-11-14 00:42:05.281372-0500 WeissProf4 [8754:662299] [MC]从私人有效用户设置中读取。
[&#34;消息&#34;:缺少必需参数,&#34;错误&#34;:1]
我不确定发生了什么,我知道PHP已成功连接到数据库,并且能够发布所需信息(使用Postman测试)。我认为这可能是Swift如何处理PHP发布的错误,尽管我绝对不是PHP专家。
答案 0 :(得分:0)
解决方案Swift4:
@IBAction func register(_ sender: Any) {
let request = NSMutableURLRequest(url: NSURL(string: "http://cgi.soic.indiana.edu/~lvweiss/prof4/register.php")! as URL)
request.httpMethod = "POST"
let postString = "username=\(user.text!)&password=\(pass.text!)&email=\(email.text!)&name=\(name.text!)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(String(describing: error))")
return
}
print("response = \(String(describing: response))")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(String(describing: responseString))")
}
task.resume()
}