【问题标题】:How do I call a SOAP web service in Swift 2?如何在 Swift 2 中调用 SOAP Web 服务?
【发布时间】:2016-03-29 12:41:56
【问题描述】:

我想为 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
        }
    }

【问题讨论】:

  • 请格式化您的代码并解释问题所在。

标签: swift web-services soap swift2


【解决方案1】:

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()
    }
}

将它与“尾随闭包”一起使用:

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

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

&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;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"&gt;&lt;soap:Body&gt;&lt;CelsiusToFahrenheitResponse xmlns="http://www.w3schools.com/xml/"&gt;&lt;CelsiusToFahrenheitResult&gt;107.6&lt;/CelsiusToFahrenheitResult&gt;&lt;/CelsiusToFahrenheitResponse&gt;&lt;/soap:Body&gt;&lt;/soap:Envelope&gt;

【讨论】:

  • 感谢您的回答。您的代码是正确的,但我只想查看 107.6。我该怎么做?
  • 不客气。我的回答向您展示了如何修复连接部分,这是您的问题。现在您必须解析 XML,为此您可以像以前一样继续使用 NSXMLParser - 您只需使用来自 NSURLSession 的数据,而不是来自 NSURLConnection 委托的数据。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
  • 2016-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多