如何向 Swift iOS 中的 php 服务器发出 HTTP 请求

How to make HTTP request to php server in Swift iOS

我正在尝试使用 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 的视频,这里是 link https://www.youtube.com/playlist?list=PLdW9lrB9HDw1Okk_wpFvB6DdY5f5lTfi1 这是播放列表中的第 6 个视频 在 iOS 上使用 Swift 的用户登录和 Register/Sign 注册示例。视频 #3

add request.HTTPMethod = "POST" 因为你正在尝试执行 post 请求,是吗?

顺便说一句:当我尝试在 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":"error","message":"Missing required field"}