这是我快速注册页面的代码。
let headers : HTTPHeaders = ["Content-Type": "application/json"]
let postString : Parameters = ["name": "com", "email": "raj123@v", "mobile": "123", "password": "123"]
let signUpUrl = "myURL/api_register.php"
Alamofire.request(signUpUrl, method: .post, parameters: postString, encoding: JSONEncoding.default, headers: headers).responseJSON {
response in
switch response.result {
case .success:
print(response)
case .failure(let eror):
print(eror)
}
这是我的php api代码:
header('Content-Type: application/json');
$return_arr = array();
$username=mysqli_real_escape_string($link,$_POST["name"]);
$email=mysqli_real_escape_string($link,$_POST["email"]);
$mobile=mysqli_real_escape_string($link,$_POST["mobile"]);
$password=mysqli_real_escape_string($link,$_POST["password"]);
$result=mysqli_query($link,"insert into users(name,email,mob,password) values('$username','$email','$mobile','$password')");
if(mysqli_num_rows($result))
{
$row_array['status']=true;
array_push($return_arr,$row_array);
}
else
{
$row_array['status']=false;
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
mysqli_close($link);
Nil条目正在插入带有alamofire的数据库。实际问题在哪里,我测试了所有但是无法获得。
如果我不使用Alamofire并且此代码也不起作用:
let signUpUrl = URL(string: "myURL/api_register.php")
var request = URLRequest(url: signUpUrl!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let postString : Parameters = ["name": "com", "email": "raj123@v", "mobile": "123", "password": "123"]
print("\(postString)")
do {
request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)
//print(request.description)
} catch let error {
print(error.localizedDescription)
displayMessage(userMessage: "Something went wrong")
return
}
答案 0 :(得分:0)
关于第二种方法,你可以使用类似的东西
let newUrl = NSURL(string:"https://.......")
let urlRequest = NSMutableURLRequest(url: newUrl! as URL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60.0)
urlRequest.httpMethod = "POST"
let body = String(format:"name=%@&email=%@","picko","werr@yahoo").data(
using: String.Encoding.utf8,allowLossyConversion: false)
urlRequest.httpBody = body
let queue = OperationQueue()
NSURLConnection.sendAsynchronousRequest(urlRequest as URLRequest, queue: queue)
{
(response: URLResponse?,data: Data?, error: Error?) in
/* Now we may have access to the data, but check if an error came back first or not */
if error == nil
{
do {
let responseDict = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
print("responseDict:\(responseDict)")
} catch let caught as NSError
{
print("Error in json \(caught)")
}
}
else if data?.count == 0 && error == nil
{
print("Nothing was downloaded")
}
else if error != nil
{
print("Error happened = \(String(describing: error))")
}
}