【问题标题】:How to make HTTP request to php server in Swift iOS如何在 Swift iOS 中向 php 服务器发出 HTTP 请求
【发布时间】:2015-05-03 18:44:47
【问题描述】:

我正在尝试使用 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

【问题讨论】:

标签: php ios swift nsurl


【解决方案1】:

添加 request.HTTPMethod = "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":"缺少必填字段"}

【讨论】:

  • 感谢重播,但添加此行后我没有收到任何消息(没有错误,也没有成功消息)
  • 我在 URL 中添加了&amp;user=root&amp;password=root,它进入了一些 PHP 页面
  • 它是因为值应该通过 post 方法发送,顺便说一句我包含了 php 脚本
  • 好的。问题是您将内容类型设置为 application/json 但您的 httpbody 不是 json 格式!当我将内容类型更改为 application/x-www-form-urlencoded 它有点工作。我得到了一些关于你的 php 脚本的其他错误...
  • 这里太长了 :) 警告:mysqli::mysqli(): (28000/1045): Access denied for user 'techicom_varun'@'localhost' (使用密码:是)在 /home/techicom/public_html/varun/ios-api/MySQLDao.php 第 21 行...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 2012-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
相关资源
最近更新 更多