Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift URLSession和URLSessionTask强制关闭连接_Swift_Urlsession - Fatal编程技术网

Swift URLSession和URLSessionTask强制关闭连接

Swift URLSession和URLSessionTask强制关闭连接,swift,urlsession,Swift,Urlsession,在我的应用程序中,我使用一些API调用web服务器。此API使用该协议。对于其中一个API,文档告诉我以下内容: The response to this function has no body in the positive case (no header line ”Content-length”). If you got a response there's something wrong in the request (in this case will be provided an

在我的应用程序中,我使用一些API调用web服务器。此API使用该协议。对于其中一个API,文档告诉我以下内容:

The response to this function has no body in the positive case (no header line ”Content-length”). If you got a response there's something wrong in the request (in this case will be provided an XML that you can parse to get details of the error).
我使用库生成/读取XML。现在,我编写了以下代码来与此API交互:

func myCallExec(url:URL, xml:String, completionHandler:@escaping (Any?, String?) -> ()) {
    var request = URLRequest(url: url)
    request.setValue("Application/xml", forHTTPHeaderField: "Content-Type")
    request.setValue("1234", forHTTPHeaderField: "Transaction")
    request.httpMethod = "POST"
    request.httpBody = Data(xml.utf8)

    var options = AEXMLOptions()
    options.parserSettings.shouldProcessNamespaces = false
    options.parserSettings.shouldReportNamespacePrefixes = false
    options.parserSettings.shouldResolveExternalEntities = false

    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
         if let _ = response, error == nil {
            if let xmlData = data {
                do {
                    let xmlDoc = try AEXMLDocument(xml: xmlData, options: options)
                    if (xmlDoc.root.children.contains(where: {$0.name == "Errortext"}) == true) {
                        completionHandler(false, xmlDoc.root["Errortext"].value)
                    }
                } catch {
                    print("error: ", error.localizedDescription)
                    completionHandler(nil, "Unable to decode")
                }
            }
        } else {
            completionHandler(true, nil)
        }
    }
    task.resume()
}
}

通过使用API,如果我遇到一些错误,它会返回一个XML并关闭连接,但是当一切正常时,我没有答案,连接不会自动终止(连接将在超时后终止),因此我必须强制终止连接。 有没有一种方法可以通过使用URLSession和/或URLSessionTask强制关闭连接? 多谢各位