我正在尝试使用Swift建立与PHP服务器的连接,但是我收到错误而且我不知道如何解决这个问题。
以下是注册按钮的代码。我正在连接到php服务器并通过post发送值以在数据库中创建一个新用户。
@IBAction func registerTapped(sender: AnyObject) {
let userId = userid.text;
let user_password = password.text;
let user_password_reaeat = repeatpassword.text;
if(userId.isEmpty || user_password.isEmpty || user_password_reaeat.isEmpty)
{
displayMyAlertMessage("All Fields are required !!");
}
if(user_password != user_password_reaeat)
{
displayMyAlertMessage("Password didn't match !!");
}
let myURL = NSURL(string: "http://tech3i.com/varun/ios-api/userRegister.php");
let request = NSMutableURLRequest(URL: myURL!);
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let postString = "userid=\(userId)&password=\(user_password)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{
data, response, error in
if(error != nil)
{
println("error=\(error)")
return
}
var err:NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
if let parseJSON = json
{
var resultValue = parseJSON["status"] as? String!;
println("result:\(resultValue)")
var isUserRegistered:Bool = false
if(resultValue=="Success")
{
isUserRegistered = true;
}
var messageToDisplay = parseJSON["message"] as String!;
if(!isUserRegistered)
{
messageToDisplay = parseJSON["message"] as String!;
}
dispatch_async(dispatch_get_main_queue(),
{
//Display Alert messsage with confirmation
var myAlert = UIAlertController(title: "Alert", message:messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "OK", style:UIAlertActionStyle.Default)
{
action in
self.dismissViewControllerAnimated(true, completion:nil);
}
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion:nil);
});
}
}
task.resume()
}
func displayMyAlertMessage(userMessage:String)
{
var myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil);
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion:nil);
}
当我点击注册按钮时,我收到以下错误
error=Error Domain=NSURLErrorDomain Code=-1017 "The operation couldn’t be completed. (NSURLErrorDomain error -1017.)" UserInfo=0x79b536b0 {NSErrorFailingURLStringKey=http://tech3i.com/varun/ios-api/userRegister.php, _kCFStreamErrorCodeKey=-1, NSErrorFailingURLKey=http://tech3i.com/varun/ios-api/userRegister.php, _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x799cd130 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1017.)"}
我的用于创建新用户的PHP脚本
<?php
require("Conn.php");
require("MySQLDao.php");
$email = htmlentities($_POST["userid"]);
$password = htmlentities($_POST["password"]);
$returnValue = array();
if(empty($email) || empty($password))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetails($email);
if(!empty($userDetails))
{
$returnValue["status"] = "error";
$returnValue["message"] = "User already exists";
echo json_encode($returnValue);
return;
}
$secure_password = md5($password); // I do this, so that user password cannot be read even by me
$result = $dao->registerUser($email,$secure_password);
if($result)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "User is registered";
echo json_encode($returnValue);
return;
}
$dao->closeConnection();
?>
我正在关注来自youtube的视频,这里是链接 https://www.youtube.com/playlist?list=PLdW9lrB9HDw1Okk_wpFvB6DdY5f5lTfi1 它是播放列表中的第6个视频 在iOS上使用Swift的用户登录和注册/注册示例。视频#3
答案 0 :(得分:1)
添加 request.HTTPMethod =“POST”,因为您正在尝试发帖请求,不是吗?
和btw:当我尝试在xcode之外使用你的URL时,请求有效(状态200)。问题似乎出现在你的php脚本中:
注意:未定义的索引:第4行/home/techicom/public_html/varun/ios-api/userRegister.php中的用户ID
注意:未定义的索引:第5行/home/techicom/public_html/varun/ios-api/userRegister.php中的密码 {“status”:“错误”,“消息”:“缺少必填字段”}