在 swift 3 和 xcode 8+ 中调用 .NET asmx

call .NET asmx in swift 3 and xcode 8+

我想使用以下代码在 swift 中为 iOS 调用 .net 框架 asmx Web 服务(soap)。

 @IBAction func buttonTest(_ sender: Any) {

    var soapMessage = "<?xml version='1.0' encoding='utf-8'?>";
    soapMessage = soapMessage + "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>";
    soapMessage = soapMessage + "<soap:Body>";
    soapMessage = soapMessage + "<LogginCustomerClub xmlns='http://tempuri.org/'>";
    soapMessage = soapMessage + "<userName>username</userName>";
    soapMessage = soapMessage + "<password>pass</password>";
    soapMessage = soapMessage + "<message>message</message>";
    soapMessage = soapMessage + "</LogginCustomerClub>";
    soapMessage = soapMessage + "</soap:Body>";
    soapMessage = soapMessage + "</soap:Envelope>";

    let urlString = "http://example.com/users.asmx"
    let url = NSURL(string: urlString)
    let theRequest = NSMutableURLRequest(url: url! as URL)

    let msgLength = String(soapMessage.characters.count)

    theRequest.addValue("text/xml; charset=utf-B", forHTTPHeaderField: "Content-Type")

    theRequest.addValue(String(msgLength), forHTTPHeaderField: "Content-Length")

    theRequest.httpMethod = "POST"

    theRequest.httpBody = soapMessage.data(using: .utf8)

    //theRequest.httpBody = soapMessage.dataUsIngEncoding (NSUTF8StringEncoding, allowLossyConversion: false) // or false

    let connection = NSURLConnection( request: theRequest as URLRequest, delegate: self, startImmediately: true)

    connection!.start()

    if (connection != nil)
    {
        var mutableData = NSMutableData.initialize()
    }
}
func connection(connection: NSURLConnection, didReceiveResponse response: URLResponse!)

{
    mutableData.length  = 0;
}

func connection(connection: NSURLConnection, didReceiveData data: NSData!)
{
     mutableData.append(data as Data)
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
    let response = NSString(data: mutableData as Data, encoding: String.Encoding.utf8.rawValue)

    let xmlParser = XMLParser(data: mutableData as Data)
    xmlParser.delegate = self
    xmlParser.parse()
    xmlParser.shouldResolveExternalEntities = true
}
    // NSXMLParserDelegate

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {

    currentElementName = elementName as NSString
}
func parser(parser: XMLParser,foundCharacters string: String?)
{
    if currentElementName == "LoginResult"{
       print(string)
    }
}

项目构建成功,但我无法得到响应。 我不知道我哪里做错了。

任何帮助将不胜感激

使用 gen4swift.com 我为 swift 生成了 asmx 类 并在此处解决了它的问题 https://github.com/drmohundro/SWXMLHash/issues/127#issuecomment-299905419

完成,现在工作