使用SOAP

时间:2015-10-01 22:29:19

标签: ios swift web-services soap

我刚刚开始使用swift为IOS编程。我已经为Android做了一个消耗一些Web服务的应用程序。我需要做同样的应用程序,但现在为IOS。 我已经可以正确调用Web服务并打印响应,但我需要访问Web服务返回的属性。啊,我有各种Web服务,其中一些返回字符串数组。这是我用来调用服务的代码

var lobj_Request = NSMutableURLRequest(URL: NSURL(string: URLString)!)
    var session = NSURLSession.sharedSession()
    var err: NSError?
    var user = nameTextField.text
    var pass = passTextField.text
    lobj_Request.HTTPMethod = "POST"
    lobj_Request.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding)
    lobj_Request.addValue(hostString, forHTTPHeaderField: "Host")
    lobj_Request.addValue("application/soap+xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    lobj_Request.addValue(String(soapMessage.characters.count), forHTTPHeaderField: "Content-Length")
    lobj_Request.addValue(SOAP_ACTION, forHTTPHeaderField: "SOAPAction")
    var task = session.dataTaskWithRequest(lobj_Request, completionHandler: {data, response, error -> Void in
        print("Response: \(response)")
        var strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("Body: \(strData)")

        if error != nil
        {
            print("Error: " + error!.description)
        }

    })
    task.resume()

我知道属性在数据中(显然),但我不知道如何访问它们。

2 个答案:

答案 0 :(得分:1)

我找到了一个非常好的库来解决这个问题。它叫做SWXMLHash。 https://github.com/drmohundro/SWXMLHash 我只这样做了:

var lobj_Request = NSMutableURLRequest(URL: NSURL(string: URLString)!)
var session = NSURLSession.sharedSession()
var err: NSError?
var user = nameTextField.text
var pass = passTextField.text
lobj_Request.HTTPMethod = "POST"
lobj_Request.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding)
lobj_Request.addValue(hostString, forHTTPHeaderField: "Host")
lobj_Request.addValue("application/soap+xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
lobj_Request.addValue(String(soapMessage.characters.count), forHTTPHeaderField: "Content-Length")
lobj_Request.addValue(SOAP_ACTION, forHTTPHeaderField: "SOAPAction")
var task = session.dataTaskWithRequest(lobj_Request, completionHandler: {data, response, error -> Void in
    print("Response: \(response)")
    var strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
    print("Body: \(strData)")

    var xml = SWXMLHash.parse(data!)

    var propertyIwant = xml["soap:Envelope"]["soap:Body"]["SoapResponse"]["SomeField"]["propertyIwant"].element?.text

    if error != nil
    {
        print("Error: " + error!.description)
    }

})
task.resume()

答案 1 :(得分:0)

如果您的Web服务返回带有JSON的字符串,则您需要解析它。 请考虑 : https://www.hackingwithswift.com/example-code/system/how-to-parse-json-using-nsjsonserialization

如果它是XML字符串: http://dubinski.org/wpis/easy-xml-parsing-in-swift/

我的意思是" strData"。