Swift XML分析器无法正确触发

时间:2018-12-17 16:00:45

标签: swift web-services web xml-parsing

我是Swift的新手,我正尝试从Web服务读取数据。返回数据,并根据解析器成功解析它。目前,我所拥有的只是返回数据时将其放置在textview中,并且可以成功完成此操作。但是返回的XML不会被解析。我在所有4个解析器函数中都有断点,但是没有一个被命中。好像他们没有被解雇。这是我的代码(此刻仅在播放,因此请很好:))

import UIKit
import Foundation


class ViewController: UIViewController, XMLParserDelegate{

var currentElementName:String = ""
var foundCharacters = ""
var parser = XMLParser()
var is_SoapMessage: String = "<?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></soap:Body></soap:Envelope>"

override func viewDidLoad() {
    super.viewDidLoad()
    parser.delegate = self
    //clear all arrays
    let Emp = EmployeeDetails()
    Emp.ID.removeAll()
    Emp.Name.removeAll()
    Emp.Mobile.removeAll()
}

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

@IBAction func GetServiceBtn(_ sender: Any) {
    Test1()
}

//Text box to see what's returned
@IBOutlet weak var OutputTxt: UITextView!

//First test of using web services
func Test1(){
    let URL: String = "http://192.168.1.106:8080/Service.asmx"

    let WebRequ = NSMutableURLRequest(url: NSURL(string: URL)! as URL)
    let session = URLSession.shared
    WebRequ.httpMethod = "POST"
    WebRequ.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
    WebRequ.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    WebRequ.addValue(String(is_SoapMessage), forHTTPHeaderField: "Content-Length")
    WebRequ.addValue("MyServices/GetEmployeesFullNames", forHTTPHeaderField: "SOAPAction")
    var Str: String = ""

    let task = session.dataTask(with: WebRequ as URLRequest, completionHandler: {data, response, error -> Void in
        let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        Str = String(strData!) as String

        if Str != ""{
            self.PopulateTxt(Detail: Str)
            self.ReadEmployeeResults(Data: data!)
            print(Str)
        }

        if error != nil
        {
            print("Error: " + error.debugDescription)
        }
    })
    task.resume()
}

//Process returned data
func ReadEmployeeResults(Data: Data){
    self.parser = XMLParser(data: Data)
    let success:Bool = parser.parse()
    if success {
        print("parse success!")
        let Emp = EmployeeDetails()
        print("Employee Name count \(Emp.Name.count)")
        print("Employee ID count \(Emp.ID.count)")
        print("Employee Mobile count \(Emp.ID.count)")
        print(Emp.Name[0])
    } else {
        print("parse failure!")
    }
}

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
    print("In Parser")
    currentElementName = elementName
    if(elementName=="Table")
    {
        let Emp = EmployeeDetails()
        for string in attributeDict {
            let strvalue = string.value as NSString
            switch string.key {
            case "Emp_ID":
                Emp.ID.append(Int(strvalue as String)!)
                break
            case "Emp_FullName":
                Emp.Name.append(strvalue as String)
                break
            case "Emp_Mobile":
                Emp.Mobile.append(strvalue as String)
                break
            default:
                break
            }
        }
    }
}

func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    print("In didEndElement Parser")
}

func parser(_ parser: XMLParser, foundCharacters string: String) {
    if currentElementName == "Emp_ID" {
        print(string)
    }
}

func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
    print("failure error: ", parseError)
}

func PopulateTxt(Detail: String){
    DispatchQueue.main.async {
        self.OutputTxt.text = Detail //code that caused error goes here
    }
}
}

class EmployeeDetails {
var Name = [String()]
var ID = [Int()]
var Mobile = [String()]
}

1 个答案:

答案 0 :(得分:1)

您没有在ReadEmployeeResults函数中设置解析器的委托。您创建的XMLParser实例与您最初创建的实例不同。

不需要您的parser属性或在viewDidLoad中设置其委托。只需在函数中创建所需的那个。

func ReadEmployeeResults(Data: Data){
    let parser = XMLParser(data: Data)
    parser.delegate = self
    let success = parser.parse()
    if success {
        print("parse success!")
        let Emp = EmployeeDetails()
        print("Employee Name count \(Emp.Name.count)")
        print("Employee ID count \(Emp.ID.count)")
        print("Employee Mobile count \(Emp.ID.count)")
        print(Emp.Name[0])
    } else {
        print("parse failure!")
    }
}

还请注意,变量和函数名称应以小写字母开头。