iOS连接不返回数据

时间:2014-12-06 19:12:02

标签: ios swift nsurlconnection

我一直在为简单的iOS用户系统制作网络服务。 PHP查询完美,但有一个问题 - iOS并没有很好地运行。数据未被接收。我该怎么办?这是我的连接类:

import Foundation

class Connection: NSObject {
    var data: NSMutableData = NSMutableData()

    func login(username: String, password: String) {
        var url: NSURL = NSURL(string: "localhost/getusers.php?username=" + username + "&password=" + password)!
        var request: NSURLRequest = NSURLRequest(URL: url)
        var conn: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
    }

    func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        println("didReceiveResponse")
    }

    func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
        self.data.appendData(conData)
    }

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        println(self.data)
    }

    deinit {
        println("deiniting")
    }
}

在这里,它被称为。

@IBAction func attemptLogin(sender: UIButton) {
        if(usernameTextField.text == "" || passwordTextField.text == "") {
            var alert = UIAlertController(title: "Error", message: "Invalid Credentials", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)

            var connection: Connection = Connection()
            connection.login(usernameTextField.text, password: passwordTextField.text)
        }
    }

最后,这是PHP服务:

error_reporting(E_ALL);
ini_set('display errors', 1);

$username = 'root';
$password = 'root';

try {
    $DBH = new PDO('mysql:host=localhost; dbname=login_test', $username, $password);
    $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $recievedUsername = $_GET['username'];
    $recievedPassword = $_GET['password'];

    $data = array($recievedUsername, $recievedPassword);

    $STH = $DBH->prepare("SELECT id, first_name, last_name FROM `users` WHERE `username` = ? AND `password` = ?");
    $STH->execute($data);

    $row = $STH->fetch(PDO::FETCH_ASSOC);
    echo json_encode($row);
} catch(PDOException $e) {
    echo $e->getMessage();
}

2 个答案:

答案 0 :(得分:1)

您是否在已编译的应用中尝试了此操作?在这种情况下,您的代码适合我。

操场的执行一旦到达代码的末尾就会停止,因此没有任何异步调用可以返回。要使游乐场继续运行,请导入XCPlayground并将此行添加到底部:

XCPSetExecutionShouldContinueIndefinitely()

答案 1 :(得分:0)

嗯,我唯一看到的是你没有为你的类实现NSURLConnectionDelegate ......它应该是

class Connection: NSObject, NSURLConnectionDelegate {...}

是否有可能当前调用NSURLConnection的非委托方法?你看过这个吗?