lundi 17 décembre 2018

Swift XML Parser not firing properly

I'm reasonably new to Swift and I'm trying to read data from a web service. The data is returned and according to the parser it was parsed successfully. All I have at the moment is when the data is returned it's to be placed in a textview and it does do this successfully. But the returned XML is not being parsed. I have breakpoints in all 4 parser functions but none of them are being hit. It's as though they are not being fired. Here's my code (this is just playing at the moment so please be nice :) )

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




Aucun commentaire:

Enregistrer un commentaire