如何在Swift 2中调用SOAP Web服务?

时间:2016-03-29 12:41:56

标签: swift web-services soap swift2

我想为Swift 2调用Web服务。但它永远不会有效。这是我的代码。

import UIKit

class ViewController: UIViewController, UITextFieldDelegate, NSURLConnectionDelegate, NSXMLParserDelegate {

    var mutableData:NSMutableData  = NSMutableData.init()
    var currentElementName:NSString = ""



    @IBOutlet var txtCelsius : UITextField!
    @IBOutlet var txtFahrenheit : UITextField!


    @IBAction func actionConvert(sender : AnyObject) {
        let celcius = txtCelsius.text

        let soapMessage = "<?xml version='1.0' encoding='utf-8'?><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/'><soap:Body><CelsiusToFahrenheit xmlns='http://www.w3schools.com/xml/'><Celsius>\(celcius)</Celsius></CelsiusToFahrenheit></soap:Body></soap:Envelope>"


        let urlString = "http://www.w3schools.com/xml/tempconvert.asmx"

        let url = NSURL(string: urlString)

        let theRequest = NSMutableURLRequest(URL: url!)


        theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        theRequest.addValue((soapMessage), forHTTPHeaderField: "Content-Length")
        theRequest.HTTPMethod = "POST"
        theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // or false

        let connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true)
        connection!.start()


    }




    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        mutableData.length = 0;
    }

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


    func connectionDidFinishLoading(connection: NSURLConnection!) {
        let xmlParser = NSXMLParser(data: mutableData)
        xmlParser.delegate = self
        xmlParser.parse()
        xmlParser.shouldResolveExternalEntities = true

    }


    func parser(parser: NSXMLParser, foundCharacters string: String) {
        if currentElementName == "CelsiusToFahrenheit" {
            txtFahrenheit.text = string
        }
    }

1 个答案:

答案 0 :(得分:8)

NSURLConnection已弃用,请改用NSURLSession

以下是使用NSURLSession和回调执行所需功能的函数示例:

func getFarenheit(celsius celsius: Int, completion: (result: String) -> Void) {
    let soapMessage = "<?xml version='1.0' encoding='utf-8'?><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/'><soap:Body><CelsiusToFahrenheit xmlns='http://www.w3schools.com/xml/'><Celsius>\(celsius)</Celsius></CelsiusToFahrenheit></soap:Body></soap:Envelope>"
    let urlString = "http://www.w3schools.com/xml/tempconvert.asmx"
    if let url = NSURL(string: urlString) {
        let theRequest = NSMutableURLRequest(URL: url)
        theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        theRequest.addValue((soapMessage), forHTTPHeaderField: "Content-Length")
        theRequest.HTTPMethod = "POST"
        theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        NSURLSession.sharedSession().dataTaskWithRequest(theRequest) { (data, response, error) in
            if error == nil {
                if let data = data, result = String(data: data, encoding: NSUTF8StringEncoding) {
                    completion(result: result)
                }
            } else {
                print(error!.debugDescription)
            }
        }.resume()
    }
}

像这样使用&#34;尾随闭包&#34;:

getFarenheit(celsius: 42) { (result) in
    print(result)
}

它打印包含XML和转换值的数据:

  

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><CelsiusToFahrenheitResponse xmlns="http://www.w3schools.com/xml/"><CelsiusToFahrenheitResult>107.6</CelsiusToFahrenheitResult></CelsiusToFahrenheitResponse></soap:Body></soap:Envelope>