NSURLSessionTask 的完成处理程序不 运行

Completion Handler of an NSURLSessionTask does not run

您好,我正在尝试从 swift 客户端在 Java 服务器上执行简单的身份验证。 java 服务器是一个 HTTPServer,它的代码接受一个带有用户名和密码的 "POST" 请求。服务器returns用户名和密码正确则为true,不通过JSON数据则为false

我认为问题出在 swift 客户端。它似乎没有 运行 任务的完成代码,因此我不相信它实际上能够连接到服务器,运行 在本地主机上。客户端代码和服务器代码如下所示。你能告诉我为什么完成代码不是 运行ning 吗?并可能给我一个关于如何解决它的答案?

Swift 客户:

import Foundation

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration)
    let usr = "TBecker"
    let pwdCode = "TBecker"
    let params:[String: AnyObject] = [
        "User" : usr,
        "Pass" : pwdCode ]

    let url = NSURL(string:"http://localhost:8080/auth")
    let request = NSMutableURLRequest(URL: url)
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.HTTPMethod = "POST"

    if (NSJSONSerialization.isValidJSONObject(params)) {
            do {
                    request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
            } catch {
                    print("catch failed")
            }
    }

    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error in

            if let httpResponse = response as? NSHTTPURLResponse {
                    if httpResponse.statusCode != 200 {
                            print("response was not 200: \(response)")
                            return
                    }
            }
            if (error != nil) {
                    print("error submitting request: \(error)")
                    return
            }

            // handle the data of the successful response here
            if (NSJSONSerialization.isValidJSONObject(data!)) {
                    do {
                            print("received data of some sort")
                            let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
                            print(result)
                    } catch {
                            print("catch failed")
                    }
            }
    })

    task.resume()

Java 服务器:

    public class HTTPRequestHandler {
    private static final String HOSTNAME = "localhost";
    private static final int PORT = 8080;
    private static final int BACKLOG = 1;

    private static final String HEADER_ALLOW = "Allow";
    private static final String HEADER_CONTENT_TYPE = "Content-Type";

    private static final Charset CHARSET = StandardCharsets.UTF_8;

    private static final int STATUS_OK = 200;
    private static final int STATUS_METHOD_NOT_ALLOWED = 405;

    private static final int NO_RESPONSE_LENGTH = -1;

    private static final String METHOD_POST = "POST";
    private static final String METHOD_OPTIONS = "OPTIONS";
    private static final String ALLOWED_METHODS = METHOD_POST + "," + METHOD_OPTIONS;

    public static void main(final String... args) throws IOException {
        final HttpServer server = HttpServer.create(new InetSocketAddress(HOSTNAME, PORT), BACKLOG);
        server.createContext("/auth", he -> {
            try {
                System.out.println("Request currently being handled");
                final Headers headers = he.getResponseHeaders();
                final String requestMethod = he.getRequestMethod().toUpperCase();
                switch (requestMethod) {
                    case METHOD_POST:
                        final Map<String, List<String>> requestParameters = getRequestParameters(he.getRequestURI());
                        // do something with the request parameters
                        final String success;

                        if (requestParameters.containsKey("User") && requestParameters.containsKey("Pass"))
                            if (requestParameters.get("User").equals("TBecker") && requestParameters.get("Pass").equals("TBecker")) {
                                    success = "['true']";
                            } else {
                                success = "['false']";
                            }
                        else
                            success = "['false']";
                        headers.set(HEADER_CONTENT_TYPE, String.format("application/json; charset=%s", CHARSET));
                        final byte[] rawSuccess = success.getBytes(CHARSET);
                        he.sendResponseHeaders(STATUS_OK, rawSuccess.length);
                        he.getResponseBody().write(rawSuccess);
                        break;
                    default:
                        headers.set(HEADER_ALLOW, ALLOWED_METHODS);
                        he.sendResponseHeaders(STATUS_METHOD_NOT_ALLOWED, NO_RESPONSE_LENGTH);
                        break;
                }
            } finally {
                System.out.println("request successfully handled");
                he.close();
            }
        });
        server.start();
    }

    private static Map<String, List<String>> getRequestParameters(final URI requestUri) {
        final Map<String, List<String>> requestParameters = new LinkedHashMap<>();
        final String requestQuery = requestUri.getRawQuery();
        if (requestQuery != null) {
            final String[] rawRequestParameters = requestQuery.split("[&;]", -1);
            for (final String rawRequestParameter : rawRequestParameters) {
                final String[] requestParameter = rawRequestParameter.split("=", 2);
                final String requestParameterName = decodeUrlComponent(requestParameter[0]);
                requestParameters.putIfAbsent(requestParameterName, new ArrayList<>());
                final String requestParameterValue = requestParameter.length > 1 ? decodeUrlComponent(requestParameter[1]) : null;
                requestParameters.get(requestParameterName).add(requestParameterValue);
            }
        }
        return requestParameters;
    }

    private static String decodeUrlComponent(final String urlComponent) {
        try {
            return URLDecoder.decode(urlComponent, CHARSET.name());
        } catch (final UnsupportedEncodingException ex) {
            throw new InternalError(ex);
        }
    }
}

谢谢!

程序似乎在服务器有机会响应之前终止。因为我猜它是一个独立的应用程序,所以没有任何东西可以同时保持它 运行,所以可能在 swift 应用程序本身内部它会保持 运行 而没有问题.