1

I am trying to make connection to PHP server using Swift but I am getting error and I don't know how to solve that.

Here is the code for register tapped button. I am making connection to php server and sending value via post to create a new user in the database.

@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);
    }

and when I tap on the register button I get the following error

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.)"}

My PHP Script for create new user

<?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();

?>

I am following video from youtube here is the link https://www.youtube.com/playlist?list=PLdW9lrB9HDw1Okk_wpFvB6DdY5f5lTfi1 its the 6th video in the playlist User login and Register/Sign up example using Swift on iOS. Video #3

4
  • 1
    possible duplicate of Error Domain=NSURLErrorDomain Code=-1017 "The operation couldn’t be Commented May 3, 2015 at 18:57
  • I already tried that its not the same. Commented May 3, 2015 at 18:59
  • why not you using Alamofire and SwiftyJSON instead NSURL? Commented May 3, 2015 at 18:59
  • I didn't know about that , thats why I am not using that Commented May 3, 2015 at 19:05

1 Answer 1

1

add request.HTTPMethod = "POST" since you are trying to do a post request, aren't you?

and btw: when i try to use your URL outside of xcode, the request works (status 200). the problem seems to be in your php script:

Notice: Undefined index: userid in /home/techicom/public_html/varun/ios-api/userRegister.php on line 4

Notice: Undefined index: password in /home/techicom/public_html/varun/ios-api/userRegister.php on line 5 {"status":"error","message":"Missing required field"}

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for replay but after adding this line I didn't get any message (no error and also there is no success message)
I added &user=root&password=root to the URL and it got to some PHP page
its because value should be sent by post method btw I included php script
ok. the problem is that you set your content-type to be application/json but your httpbody is not json formatted! when i change content-type to be application/x-www-form-urlencoded it kinda works. i get some other errors regarding your php script though...
it's too long to post it here :) Warning: mysqli::mysqli(): (28000/1045): Access denied for user 'techicom_varun'@'localhost' (using password: YES) in /home/techicom/public_html/varun/ios-api/MySQLDao.php on line 21...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.