如何在Swift中解析XML Web服务?

前端之家收集整理的这篇文章主要介绍了如何在Swift中解析XML Web服务?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我不知道如何在下面的代码解析..
有人可以
func callService(usr: String,pwdCode: String) {

    let url = NSURL(string: "http://inspect.dev.cbre.eu/SyncServices/api/jobmanagement/PlusContactAuthenticationPost")
    var xmlParse:NSString  = ""
    var data : NSData!
    let request = NSMutableURLRequest(URL: url!)
    request.setValue("application/json; charset=utf-8",forHTTPHeaderField: "Content-Type")
     request.HTTPMethod = "POST"
    let dictionary = ["email": usr,"userPwd": pwdCode]
    var error: NSError?
    if let body = NSJSONSerialization.dataWithJSONObject(dictionary,options: nil,error: &error) {
        request.HTTPBody = body
    } else {
        println("JSON error: \(error)")
    }

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        (data,response,error) in
        println(NSString(data: data,encoding: NSUTF8StringEncoding))

        // xmlParse=NSString(data: data,encoding: NSUTF8StringEncoding)!
        // let data = (xmlParse as NSString).dataUsingEncoding(NSUTF8StringEncoding)
        // NSXMLParser(data : NSData)

        // xmlParse=NSString(data: data,encoding: NSUTF8StringEncoding)!
        // xmlParse=response
        // println(xmlParse)
    }
    task.resume()

}
您应该在请求的完成处理程序中使用NSXMLParser:
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    (data,error) in

    if data == nil {
        println("dataTaskWithRequest error: \(error)")
        return
    }

    let parser = NSXMLParser(data: data)
    parser.delegate = self
    parser.parse()

    // you can now check the value of the `success` variable here
}
task.resume()

// but obvIoUsly don't try to use it here here

显然,上述假定您(a)定义了您的视图控制器以符合NSXMLParserDelegate和(b)已实现NSXMLParserDelegate方法,例如就像是:

var elementValue: String?
var success = false

func parser(parser: NSXMLParser,didStartElement elementName: String,namespaceURI: String?,qualifiedName qName: String?,attributes attributeDict: [NSObject : AnyObject]) {
    if elementName == "success" {
        elementValue = String()
    }
}

func parser(parser: NSXMLParser,foundCharacters string: String?) {
    if elementValue != nil {
        elementValue! += string
    }
}

func parser(parser: NSXMLParser,didEndElement elementName: String,qualifiedName qName: String?) {
    if elementName == "success" {
        if elementValue == "true" {
            success = true
        }
        elementValue = nil
    }
}

func parser(parser: NSXMLParser,parseErrorOccurred parseError: NSError) {
    println("parseErrorOccurred: \(parseError)")
}
原文链接:https://www.f2er.com/swift/318942.html

猜你在找的Swift相关文章