在Swift中登录后返回url的内容?

时间:2016-06-12 23:01:33

标签: php json swift

所以我有几条线路将会#34;登录"到网页,他们获取内容并将其打印到控制台,但我无法弄清楚如何从"任务"中获取结果。并在稍后的代码中使用它们。

let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8888/mobilelogin.php")!)
    request.HTTPMethod = "POST"
    let username = email_input.text;
    let password = password_input.text;
    var postString = "username="
    postString += username!
    postString += "&password="
    postString += password!
    print(postString);
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    print(request.HTTPBody);
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in guard error == nil && data != nil
        else {
            // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
            // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
            return
        }

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
        print("responseString = \(responseString)");
        return

    }
    print("This is the task string")
    task.resume()

1 个答案:

答案 0 :(得分:0)

你无法从关闭中返回,你需要使用"回调"。

我们为您的代码创建了一个函数:

func getData(username username: String, password: String)

但我们不是添加返回类型,而是添加一个回调,此处命名为"完成":

func getData(username username: String, password: String, completion: (response: String)->()) {

}

在函数内部,我们在数据可用的位置使用此回调:

func getData(username username: String, password: String, completion: (response: String)->()) {
    let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8888/mobilelogin.php")!)
    request.HTTPMethod = "POST"
    var postString = "username="
    postString += username
    postString += "&password="
    postString += password
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard let data = data where error == nil else {
            fatalError(error!.debugDescription)
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
            print("response = \(response)")
            fatalError("statusCode should be 200, but is \(httpStatus.statusCode)")
        }

        guard let str = String(data: data, encoding: NSUTF8StringEncoding) else {
            fatalError("impossible to get string from data")
        }

        completion(response: str)

    }
    task.resume()
}

你会像这样使用它:

getData(username: email_input.text!, password: password_input.text!) { (response) in
    print(response)
}